简体   繁体   English

全局变量不适用于线程 - Python

[英]Global Variable not working with Threads - Python

I want to be able to change the background colour of a Tkinter frame in a thread, the frame is declared in a separate function.我希望能够在线程中更改 Tkinter 框架的背景颜色,该框架是在单独的函数中声明的。 I receive the following error when I run the following code.运行以下代码时收到以下错误。

Error: NameError: name 'mainScreen' is not defined错误: NameError: name 'mainScreen' is not defined

Code:代码:

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

Any help is appreciated.任何帮助表示赞赏。

You can replace your whole code with this:你可以用这个替换你的整个代码:

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

And if you want to change colours you can do something like this:如果你想改变颜色,你可以这样做:

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.

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