I was doing a program so I could execute a selenium script when I pressed a button on a interface made in tkinter but I had the problem that when I runned the function that would execute the webdriver it told me that running is a local variable and I was calling it before assigning it although I assinged it as a global variable.
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()
Then I tried passign running as an argument but then the error is that when I use the function and change the value it changes in a local level and when I run the next function that uses that variable it has the wrong value. I would like to know how I can do to make the function recognize that variable as a global variable. Thank you all
I solved adding adding global before running as @formicaman told me and it looks like this if anyone needs it
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()