Home > Blockchain >  Can't use results outside of functions
Can't use results outside of functions

Time:01-30

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.

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

CodePudding user response:

Your variables have a local scope inside the functions they were created in.

You can use a class initialized outside the function calls to hold the selected values, or global variables which are generally frowned upon.

CodePudding user response:

You can achieve your goal by making use of the global keyword. Use this: 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():
    global year_name = var_one.get()
    print(year_name)

def choose_month():
    global 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()
  •  Tags:  
  • Related