[英]Global Variable not working with Threads - Python
我希望能夠在線程中更改 Tkinter 框架的背景顏色,該框架是在單獨的函數中聲明的。 運行以下代碼時收到以下錯誤。
錯誤: NameError: name 'mainScreen' is not defined
代碼:
import tkinter as tk
from tkinter import ttk
from multiprocessing import Process
def main():
global mainScreen
root = tk.Tk()
root.geometry('1040x540+50+50')
mainScreen = tk.Frame(root, width = 1040, height = 540)
mainScreen.place(x=0, y=0)
root.mainloop()
def test(): # This function is in a thread as it will be run as a loop.
while True:
mainScreen.configure(bg='red')
if __name__ == '__main__':
p2 = Process(target = test)
p2.start()
main()
任何幫助表示贊賞。
你可以用這個替換你的整個代碼:
import tkinter as tk
def main():
global mainScreen
root = tk.Tk()
root.geometry('1040x540+50+50')
mainScreen = tk.Frame(root, width=1040, height=540)
mainScreen.place(x=0, y=0)
mainScreen.configure(bg='red')
root.mainloop()
if __name__ == '__main__':
main()
如果你想改變顏色,你可以這樣做:
import time
import tkinter as tk
from threading import Thread
def test(mainScreen): # This function is in a thread as it will be run as a loop.
while True:
try:
time.sleep(1)
mainScreen.configure(bg='red')
time.sleep(1)
mainScreen.configure(bg='blue')
except RuntimeError:
break
if __name__ == '__main__':
root = tk.Tk()
root.geometry('1040x540+50+50')
mainScreen = tk.Frame(root, width=1040, height=540)
mainScreen.place(x=0, y=0)
p2 = Thread(target=test, args=(mainScreen,))
p2.start()
root.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.