Search code examples
pythonvariablestkinterbuttoncombobox

How to convert a local variable into a global variable?


This is a snippet of my code. I am trying to convert the local variable (choice) into a global variable so I can use the value it is holding later in the code, but I am unsure to how to do this. The code has no errors.

from tkinter import ttk
from tkinter import messagebox
from tkinter import Tk

root = Tk()
root.geometry("400x400")
cmb = ttk.Combobox(root, width="10",
values=("us","mexico","uk","france"))
cmb.place(relx="0.1",rely="0.1")

def checkcmbo():
    choice = cmb.get()

btn = ttk.Button(root, text="Get Value",command=checkcmbo)
btn.place(relx="0.5",rely="0.1")

URL='https://www.worldometers.info/coronavirus/country/'+choice+'/'
#this is where I need to use the value in the local variable

root.mainloop()

#Web scrapes the data containing the dates and daily deaths
URL='https://www.worldometers.info/coronavirus/country/'+choice+'/'
#### This is where I need to use the value in the local variable ####
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
results=soup.find_all("div", {"class": "col-md-12"})
data=results[4]
script = data.find('script')
string = script.string

Solution

  • I believe you do this :

    from tkinter import ttk
    from tkinter import messagebox
    from tkinter import Tk
    
    root = Tk()
    root.geometry("400x400")
    cmb = ttk.Combobox(root, width="10", 
    values=("us","mexico","uk","france"))
    cmb.place(relx="0.1",rely="0.1")
    
    def checkcmbo():
        URL='https://www.worldometers.info/coronavirus/country/'+cmb.get()+'/'
        page = requests.get(URL)
        soup = BeautifulSoup(page.content, "html.parser")
        results=soup.find_all("div", {"class": "col-md-12"})
        data=results[4]
        script = data.find('script')
        string = script.string
    
    btn = ttk.Button(root, text="Get Value",command=checkcmbo)
    btn.pack()
    
    root.mainloop()
    

    I hadn't saw your complete code, so I can't be sure but this should solve your problem.