Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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()
like image 830
Gareth France Avatar asked Oct 19 '25 07:10

Gareth France


2 Answers

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

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

like image 59
Wrath Avatar answered Oct 21 '25 20:10

Wrath


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.

like image 38
Guenther Leyen Avatar answered Oct 21 '25 20:10

Guenther Leyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!