Gareth France
Gareth France

Reputation: 53

How do I get the dimensions of the canvas in tkinter?

I am experimenting with the below code to firm up some ideas I have. However it does not run because the canvas appears to not have any dimensions until the end of the code, by which time it is too late to do anything about it. How can I identify the dimensions of the canvas in order to use it in the line 'divw = int(screen_width / 100)'?

#!/usr/bin/python3
from tkinter import *


window = Tk()
window.title('Timetable')
window.attributes('-zoomed', True)
screen_width = window.winfo_width()
screen_height = window.winfo_height()
canvas = Canvas(window, width = window.winfo_screenwidth(), height = window.winfo_screenheight(), bg='steelblue')

canvas.pack()
image = PhotoImage(file='blank.png')

screen_width = window.winfo_width()
screen_height = window.winfo_height()
divw = int(screen_width / 100)
print (divw)
for i in range(0, divw):
    print (i)
    canvas.create_image(i * 100+50, 50, anchor = NW, image=image)
mainloop()

Upvotes: 4

Views: 7927

Answers (2)

Guenther Leyen
Guenther Leyen

Reputation: 31

Try doing this:

try:
    import Tkinter as tk
except:
    import tkinter as tk

class myCanvas(tk.Frame):
    def __init__(self, root):
        #self.root = root
        self.w = 600
        self.h = 400
        self.canvas = tk.Canvas(root, width=self.w, height=self.h)
        self.canvas.pack( fill=tk.BOTH, expand=tk.YES)

        root.bind('<Configure>', self.resize)

    def resize(self, event):
        self.w = event.width
        self.h = event.height
        print ('width  = {}, height = {}'.format(self.w, self.h))

root = tk.Tk()   
root.title('myCanvas')
myCanvas(root)
root.mainloop()        

works for me.

Upvotes: 2

Dowon Cha
Dowon Cha

Reputation: 84

Try calling tkinter.update() before window.winfo_width()

https://stackoverflow.com/a/49216638/8425705

Upvotes: 2

Related Questions