简体   繁体   中英

How to update global variable in infinite loop using multiprocess

I have the following simple code. There is one button and entry widget.

When I clicked button, changeText read entry_widget value and assign to 'var'. mainWindow and InfiniteLoop are running same time. But in InfiniteLoop variable var's value doesn't change. How to change its value?

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

You need to call changeText method to update value. If you want to do this inside InfiniteLoop;

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

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

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