如何使用多进程在无限循环中更新全局变量

时间:2018-07-27 07:11:28

标签: python textbox global multiprocess

我有以下简单代码。有一个按钮和输入小部件。

当我单击按钮时,changeText读取entry_widget值并将其分配给'var'。 mainWindow和InfiniteLoop在同一时间运行。但是在InfiniteLoop变量中var的值不变。如何更改其值?

import tkinter as Tk
from multiprocessing import Manager, Process
import time
var = 'Unchanged'

root = Tk.Tk()
root.geometry('740x306')
root.title("Performance")

id_label = Tk.Label(master=root, text="Id: ")
id_label.pack()

entry_widget = Tk.Entry(master=root, font=30)
entry_widget.pack()

def changeText():
  global var
  var = entry_widget.get() #var is changed here. example var's value is: a
  print_var() # var = a and printing a. 
def print_var():
  print(var) # var's value is a and its working here.

def aaa():
  id_label.config(font=30)
  id_label.place(x=10, y=5)
  entry_widget.place(x=33, y=5)


  sumbit_button = Tk.Button(master=root, text='Sumbit', command=changeText)
  sumbit_button.pack()
  sumbit_button.place(x=250, y=2)
  Tk.mainloop()

def forLoop():
  while True:
    time.sleep(0.1)
    print_var() #doesn't work here. print Unchanged

if __name__ == '__main__':
    p1 = Process(target=aaa)
    p1.start()
    p2 = Process(target=forLoop)
    p2.start()
    p1.join()
    p2.join()

1 个答案:

答案 0 :(得分:0)

您需要调用changeText方法来更新值。如果要在InfiniteLoop中执行此操作;

#Button's command
  def changeText():
    global var
    var = entry_widget.get()
    return var

def InfiniteLoop():
  var = changeText()
  while True:
    print(var)