简体   繁体   English

python 从 tkinter 小部件设置全局变量

[英]python set global variable from tkinter widget

I was playing with the tkinter and multiprocessing package and global variable.我在玩 tkinter 和多处理 package 和全局变量。 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.当它被释放时,它的值不会保留,而是恢复到它之前的 state。 Your help is really appreciated.非常感谢您的帮助。 Here is the MVP.这里是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()

You have created a brand new PROCESS to do the monitoring.您已经创建了一个全新的 PROCESS 来进行监控。 That process has its own memory space, completely separate from the one running the GUI.该进程有自己的 memory 空间,与运行 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.您会看到值按预期更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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