我无法让 tkinters Canvas 在初始化期间为我提供可见区域,我需要在这段时间内获取可见区域的原因是我需要坐标来确定创建后立即向用户显示的内容。
Canvas 将在 __init__
之后正确打印其区域。通过按下按钮,但在 .grid()
之后调用该函数时则不会里面__init__
try:
import tkinter as tk
except:
import Tkinter as tk
class app(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.grid_columnconfigure(0,weight=1)
self.grid_rowconfigure(1,weight=1)
self.vis_area_btn = tk.Button(self,text="Print Visible Area",
command=self.prnt_vis_area)
self.canvas = tk.Canvas(self,bg="white",highlightthickness=0)
self.vis_area_btn.grid(row=0,column=0,sticky="nswe")
self.canvas.grid(row=1,column=0,sticky="nswe")
self.prnt_vis_area()
def prnt_vis_area(self,event=None):
#self.canvas.configure(scrollregion=(0,0,1,1))
x1 = self.canvas.canvasx(0)
y1 = self.canvas.canvasy(0)
x2 = self.canvas.canvasx(self.canvas.winfo_width())
y2 = self.canvas.canvasy(self.canvas.winfo_height())
print (x1,y1,x2,y2)
root = app()
root.mainloop()
最佳答案
这是一个非常简单的修复。
tkinter 有一个名为 .update()
的函数,其解释为 here :
Processes all pending events, calls event callbacks, completes any pending geometry management, redraws widgets as necessary, and calls all pending idle tasks. This method should be used with care, since it may lead to really nasty race conditions if called from the wrong place (from within an event callback, for example, or from a function that can in any way be called from an event callback, etc.). When in doubt, use update_idletasks instead.
总之,您需要知道的是,在调用 self.prnt_vis_area()
之前添加 self.canvas.update()
可以解决您的问题。
def __init__(self):
tk.Tk.__init__(self)
self.grid_columnconfigure(0,weight=1)
self.grid_rowconfigure(1,weight=1)
self.vis_area_btn = tk.Button(self,text="Print Visible Area",
command=self.prnt_vis_area)
self.canvas = tk.Canvas(self,bg="white",highlightthickness=0)
self.vis_area_btn.grid(row=0,column=0,sticky="nswe")
self.canvas.grid(row=1,column=0,sticky="nswe")
self.canvas.update() #here
self.prnt_vis_area()
关于Python tkinter Canvas 在启动期间获取可见区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47092784/