如何更新 Tkinter 窗口的屏幕(画布) [英] How do I update the screen (canvas) of a Tkinter window
问题描述
我进行了广泛的搜索,但没有找到答案.
I have searched quite extensively and haven't found the answer.
我已经找到并将我的问题简化为这个例子.
I have tracked down and reduced my problem to this example.
from Tkinter import *
class A:
def __init__(self):
self.var = True
obj = A()
def meth():
obj.var = False
paintGui()
def paintGui():
master = Tk()
w = Canvas(master, width=200, height=100)
w.pack()
w.create_rectangle(50, 25, 150, 75, fill="blue", tags="rect")
btn = Button(master, text="Cerrar Mesa",command=meth)
btn.pack(side=BOTTOM)
if obj.var == False:
w.itemconfig("rect", fill="red")
mainloop()
paintGui()
如你所见,矩形有一个条件itemconfig
.
As you can see the rectangle has a conditional itemconfig
.
meth()
中的 paintGui()
行只是为了表明代码正在运行,并且当 obj.var
为 时>False
然后它变成红色.
The line paintGui()
inside meth()
is only to show that the code is working and when obj.var
is False
then it is turning to red.
我的问题是原来的窗口(它下面的那个)仍然是蓝色的.
My problem is that the original window (the one underneath it) is still blue.
我可以杀死原始窗口并保留新窗口,但这应该没有必要.
I could kill the original window and leave the new one, but that shouldn't be necessary.
所以我有两个问题:
- 我该如何解决这个问题?
我尝试过 after()
和 update_idletaskes
但它们似乎都不起作用,尽管我可能使用不正确.
I have tried after()
and update_idletaskes
but none of them seem to work though I may be using the incorrectly.
- 这里有什么问题?
我认为 tkinter 应该处于循环中.当我更改 var
的值时,它不应该循环并重新绘制屏幕并将 obj.var == False
评估为 True
吗?
I thouth tkinter was suposed to be in a loop. When I change the value of var
shouldn't it loop and re-paint the screen and evaluate obj.var == False
as True
?
推荐答案
每次调用 paintGui
都会创建一个全新的窗口.那是因为您正在调用 Tk()
,创建新的小部件,并运行一个新的 mainloop
.这些事情只需要发生一次,所以把它们从 paintGui
函数中去掉.
Every time you call paintGui
it is creating a brand new window. That's because you are calling Tk()
, creating new widgets, and running a new mainloop
. These things only need to happen once, so take them out of the paintGui
function.
这个经过最少修改的代码版本可以满足您的需求.
This minimally modified version of your code does what you want.
from Tkinter import *
class A:
def __init__(self):
self.var = True
obj = A()
def meth():
obj.var = False
paintGui()
def paintGui():
if obj.var == False:
w.itemconfig("rect", fill="red")
master = Tk()
w = Canvas(master, width=200, height=100)
w.pack()
w.create_rectangle(50, 25, 150, 75, fill="blue", tags="rect")
btn = Button(master, text="Cerrar Mesa",command=meth)
btn.pack(side=BOTTOM)
mainloop()
这篇关于如何更新 Tkinter 窗口的屏幕(画布)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!