0

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 labelto my code, it gives me the same error. I'm a python newbie. What am I doing wrong?

Tim
  • 155
  • 1
  • 11
  • 1
    Possible duplicate of [Python - How to make a local variable (inside a function) global](https://stackoverflow.com/questions/14051916/python-how-to-make-a-local-variable-inside-a-function-global) – Taohidul Islam Jun 10 '18 at 15:05
  • You didn't show your code with `global label` - I'll assume that you added it to both functions. Anyway, if you use threads this way, you have no guarantee that `label` will have been defined in `window()` before you try to use it in `loop()`. Are you sure that you want to use threads here? – Thierry Lathuille Jun 10 '18 at 15:24
  • I am not sure what to do. The reason for why I need threads, is because I need to run a while loop while a window is running. But I don't how to define label and use it in my other functions. – Tim Jun 10 '18 at 15:34
  • See for example https://stackoverflow.com/questions/459083/how-do-you-run-your-own-code-alongside-tkinters-event-loop/1835036 . Using threads with tkinter will probably get you into problems unless you really know what you are doing. That's probably why the answer you accepted on your previous question, which recommended you to use them, got downvoted: it's bad advice. – Thierry Lathuille Jun 10 '18 at 16:24

1 Answers1

0

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()
Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39