【问题标题】:How do I get the dimensions of the canvas in tkinter?如何在 tkinter 中获取画布的尺寸?
【发布时间】:2018-11-24 16:30:35
【问题描述】:

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

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

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

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

    【讨论】:

    • NameError: name 'tkinter' is not defined
    • @DowonCha 我想你的意思是window.update(),这是一个小部件方法,而不是全局 tkinter 函数。另外,你不必强制更新整个GUI,你可以做window.update_idletasks()
    • 谢谢你们两位。完美运行。
    【解决方案2】:

    尝试这样做:

    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()        
    

    为我工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多