Skip to main content
 首页 » 编程设计

python之如何在 tkinter 中获取 Canvas 的尺寸

2024年09月07日11telwanggs

我正在尝试使用以下代码来巩固我的一些想法。但是它不会运行,因为在代码结束之前 Canvas 似乎没有任何尺寸,到那时再做任何事情都为时已晚。如何识别 Canvas 的尺寸以便在“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() 

请您参考如下方法:

尝试在 window.winfo_width() 之前调用 tkinter.update()

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