Python 函数中未检测到全局变量

Python Global Variable Not Detected in Function

我正在做一个程序,所以当我在 tkinter 制作的界面上按下按钮时,我可以执行 selenium 脚本,但是我遇到了问题,当我 运行ned 将执行 webdriver 的函数时,它告诉我 运行ning 是一个局部变量,我在分配它之前调用它,尽管我将它作为一个全局变量。

from selenium import webdriver
from time import sleep
from tkinter import *

root = Tk()

running = False

def start():
    if running == False:
        running = True
        browser = webdriver.Chrome("E:\webdrivers\chromedriver")
        browser.maximize_window()
        browser.get("https://google.com")
        print("The program is running")
    else:
        print("The program is already running")

def stop():
    if running == False:
        print("The program is not running")
    else:
        running = False
        browser.quit()
        print("Program killed")

startButton = Button(root, text="Start", padx=80, pady=80, command=start, fg="#ff0066", bg="#1a1a1a")
stopButton = Button(root, text="Stop", padx=80, pady=80, command=stop, fg="#1a1a1a", bg="#ff0066")

startButton.pack()
stopButton.pack()

root.mainloop()

然后我尝试将 运行ning 作为参数传递,但错误是当我使用该函数并更改值时它会在局部级别发生变化,而当我 运行 下一个函数时使用该变量的它具有错误的值。我想知道如何使函数将该变量识别为全局变量。谢谢大家

正如@formicaman 告诉我的那样,我解决了在 运行 之前添加全局的问题,如果有人需要它,它看起来像这样

from selenium import webdriver
from time import sleep
from tkinter import *

root = Tk()

running = False

def start():
    global running
    if running == False:
        running = True
        browser = webdriver.Chrome("E:\webdrivers\chromedriver")
        browser.maximize_window()
        browser.get("https://google.com")
        print("The program is running")
    else:
        print("The program is already running")

def stop():
    global running
    if running == False:
        print("The program is not running")
    else:
        running = False
        browser.quit()
        print("Program killed")

startButton = Button(root, text="Start", padx=80, pady=80, command=start, fg="#ff0066", bg="#1a1a1a")
stopButton = Button(root, text="Stop", padx=80, pady=80, command=stop, fg="#1a1a1a", bg="#ff0066")

startButton.pack()
stopButton.pack()

root.mainloop()