Python - Change a local variable to a global
当我运行代码时,会得到一个名称错误,因为没有定义"label"。它是一个局部变量,但我希望它是一个全局变量。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | from tkinter import * from threading import Thread def window(): root = Tk() Window=Frame(root) Window.pack(side=TOP) label = Label(Window, text="Window").grid() root.mainloop() def loop(): label.configure(text="Something else") if __name__ == '__main__': Thread(target = window).start() Thread(target = loop).start() |
当我在代码中添加
您需要在全局范围内声明您的变量。
请注意,当您使用多线程时,不确定哪个线程将首先运行。你需要控制它一个接一个地运行。在这段代码中,我通过
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | from tkinter import * from threading import Thread import time global label #global variable label def window(): root = Tk() Window=Frame(root) Window.pack(side=TOP) global label #this line is needed if you want to make any change on label variable label = Label(Window, text="Window") #updated label.grid() #updated root.mainloop() def loop(): time.sleep(1) #wait for one second and give chance other thread to run first global label label.configure(text="Something else") if __name__ == '__main__': Thread(target = window).start() Thread(target = loop).start() |