Home > Blockchain >  python set global variable from tkinter widget
python set global variable from tkinter widget

Time:11-19

I was playing with the tkinter and multiprocessing package and global variable. I am not able to set the variable while I press the button. When it is released, its value doesn't remain and is restored to its previous state. Your help is really appreciated. Here is the MVP.

from multiprocessing import Process
from tkinter import *
import time
root = Tk()
var_a = 10


def set_callback():
    global var_a
    var_a = int(e1.get())
    print(var_a)


def pro_function():
    while True:
        print(var_a)
        time.sleep(0.1)


e1 = Entry(root)
e1.pack(pady=12)
button1 = Button(root, text="Set Var", command = set_callback )
button1.pack(pady=12)


if __name__ == '__main__':

    root.geometry('350x218')
    root.title("PythonLobby")
    x = Process(target=pro_function)
    x.start()
    root.mainloop()
    x.join()

CodePudding user response:

You have created a brand new PROCESS to do the monitoring. That process has its own memory space, completely separate from the one running the GUI. If you had used a simple thread to do the monitoring, you would see that it worked just fine. Just replace

    x = Process(target=pro_function)

with

    x = threading.Thread(target=pro_function)

and you'll see that the value updates as expected.

  • Related