Python Forum
[Tkinter] Why is it so difficult to just ouput an image where I want?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] Why is it so difficult to just ouput an image where I want?
#8
Hi jpezz

You can't place a Canvas directly on the screen. It must be embedded on the main window. Here some different placements of an image in a tk-Application:

# -*- coding: utf-8 -*

try:
    # Import Tkinter for Python 2.xx
    import Tkinter as tk
except ImportError:
    # Or import Tkinter for Python 3.xx
    import tkinter as tk
    
from PIL import Image, ImageTk

MAIN_WIN_TITLE = "Image Placements"
MAIN_WIN_XPOS = 100
MAIN_WIN_YPOS = 100
MAIN_WIN_WIDTH = 800
MAIN_WIN_HEIGHT = 600

CANVAS_XPOS = 50
CANVAS_YPOS = 50
CANVAS_WIDTH = 400
CANVAS_HEIGHT = 400
CANVAS_BG = 'steelblue'
 
root = tk.Tk()
root.title(MAIN_WIN_TITLE)

# Placement of the main window
root.geometry("{}x{}+{}+{}".format(
    MAIN_WIN_WIDTH, MAIN_WIN_HEIGHT, MAIN_WIN_XPOS, MAIN_WIN_YPOS))

# Get the .jpg image and convert it to tkinter format
image = Image.open("pngs/a.jpg")
root.test_image = ImageTk.PhotoImage(image)

# Placement of a canvas on the main window 
canvas = tk.Canvas(root, bg=CANVAS_BG)
canvas.place(x=CANVAS_XPOS, y=CANVAS_YPOS, width=CANVAS_WIDTH,
    height=CANVAS_HEIGHT)
    
# Place the image as canvas image object directly on the canvas by
# useage of coordinates
canvas.create_image(15, 25, image=root.test_image, anchor='nw')

# Create a label widget containing the image and place it in a canvas
# window object on the canvas
image_label = tk.Label(canvas, text="Image Label placed\non canvas",
    compound='bottom', image=root.test_image)
canvas.create_window(200, 200, anchor='nw', window=image_label)

# Create a label widget containig the image and place it directly on
# the main window
image_label = tk.Label(root, text="Image Label placed\non main window",
    compound='bottom', image=root.test_image)
image_label.place(x=500, y=50)

root.mainloop()
wuf :-)
Reply


Messages In This Thread
RE: Why is it so difficult to just ouput an image where I want? - by wuf - Apr-05-2019, 04:26 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Switching from tkinter to gtk is difficult! snakes 1 1,505 Aug-08-2022, 10:35 PM
Last Post: woooee

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020