简体   繁体   中英

Python - Change a local variable to a global

When I run my code, I get a NameError, because "label" is not defined. It is a local variable, but I want it to be a global variable.

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

When I add global label to my code, it gives me the same error. I'm a python newbie. What am I doing wrong?

You need to declare your variable in global scope.

Please note that, when you use multi-thread then it's not certain that which thread will run first. You need to control it to run one after another. In this code I have delayed the the second thread by sleep() function. You can do this :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM