I’ve created a tiny script using tkinter to get values from two dropdowns. One for selecting year and the other for selcting month. The script appears to be working fine as long as I print the values of the dropdowns within the respective functions.
I wish to print the result just before the mainloop where I’ve defined the print statement.
mainloop
from tkinter import * master = Tk() master.geometry("200x200") master.minsize(200, 200) master.maxsize(200, 200) options_one = ['2019''2020','2021'] options_two = ["Jan","Feb","Mar"] var_one = StringVar(master) var_one.set('Year') OptionMenu(master, var_one, *options_one).pack() var_two = StringVar(master) var_two.set('Month') OptionMenu(master, var_two, *options_two).pack() def choose_year(): year_name = var_one.get() print(year_name) def choose_month(): month_name = var_two.get() print(month_name) Button(master,command=choose_year).pack() Button(master,command=choose_month).pack() print(f"It was year {year_name} and the month was {month_name}") mainloop()
In your current code, the variables year_name and month_name are defined within the functions choose_year and choose_month, respectively. These variables have local scope, meaning they are only accessible within the functions where they are defined.
year_name
month_name
choose_year
choose_month
To print these values just before the mainloop, you need to make these variables global so that they can be accessed outside the functions. You can achieve this by declaring them as global variables in the functions.
Here’s an updated version of your code:
from tkinter import * master = Tk() master.geometry("200x200") master.minsize(200, 200) master.maxsize(200, 200) options_one = ['2019', '2020', '2021'] options_two = ["Jan", "Feb", "Mar"] var_one = StringVar(master) var_one.set('Year') OptionMenu(master, var_one, *options_one).pack() var_two = StringVar(master) var_two.set('Month') OptionMenu(master, var_two, *options_two).pack() year_name = None # Declare as a global variable month_name = None # Declare as a global variable def choose_year(): global year_name year_name = var_one.get() print(year_name) def choose_month(): global month_name month_name = var_two.get() print(month_name) Button(master, command=choose_year).pack() Button(master, command=choose_month).pack() print(f"It was year {year_name} and the month was {month_name}") mainloop()
Now, the variables year_name and month_name are declared as global variables, and you can access them outside the functions. Note that this approach uses global variables, and while it solves the issue, it’s often recommended to avoid global variables when possible.