0
根據我的理解,window.mainloop()
不斷重複GUI代碼,以便窗口及其小部件保留在屏幕上。爲什麼因此可以更新變量(如canvastext
)並保持更新?當然,window.mainloop()
的邏輯會覆蓋canvastext
,以便它再次具有文本值「Hi」而不是新的spinbox值? 這可能是我完全誤解了window.mainloop()
的作用,但如果它確實讓程序在代碼中循環,那麼爲什麼變量沒有重新分配它們的原始值?瞭解Tkinter mainloop()的邏輯以及爲什麼變量不會被重新賦值爲原始值?
from tkinter import *
x = 10
y = 10
a = 100
b = 100
def hello():
#print spin value
print ("Spin Value:")
number = v.get()
print(number)
#update text with variable value
txt = v.get()
global canvastext
canvas1.delete(canvastext)
canvas1.update()
canvastext = canvas1.create_text(50, 50, text = txt)
window = Tk()
window.geometry("500x500")
#canvas and drawing
canvas1=Canvas(window, height = 200, width = 400)
canvas1.grid(row=0, column=0, sticky=W)
coord = [x, y, a, b]
rect = canvas1.create_rectangle(*coord, outline="#fb0", fill="#fb0")
canvastext = canvas1.create_text(50, 50, text ="Hi")
# create a toplevel menu
menubar = Menu(window)
firstmenu = Menu(menubar, tearoff=0)
firstmenu.add_command(label="Hello!", command=hello)
firstmenu.add_command(label="Quit!", command=window.destroy)
menubar.add_cascade(label="Menu1", menu=firstmenu)
secondmenu = Menu(menubar, tearoff=0)
secondmenu.add_command(label="Hi!", command=hello)
secondmenu.add_command(label="Quit!", command=window.destroy)
menubar.add_cascade(label="Menu2", menu=secondmenu)
window.config(menu=menubar)
#spinboxes and capturing value
v=IntVar()
spin = Spinbox(window, textvariable=v, from_=1, to = 10)
spin.grid(row=1, column = 0, sticky= W)
window.mainloop()
再次感謝布萊恩。這現在很合理。我的誤解是認爲主循環在每個循環中重新執行,所以我認爲如果函數更新了canvastext變量,當下面的主循環迭代發生時它將被重寫。但是現在知道主代碼不會一遍又一遍地執行,而只是等待事件,爲什麼變量保持改變是有意義的。再次感謝! – sw123456 2014-09-28 20:46:10