Reputation: 103
Trying to make 9 sets of 4 radio buttons, with values 1-2-3-4. I want to add up the values after a button is clicked
Whenever I try to call a method with the radio button I get a traceback:
File "depression.py", line 9, in print_var
print(var.get())
NameError: name 'var' is not defined
This is my code:
import tkinter as tk
from tkinter.ttk import *
def print_var():
print(var.get())
MODES = [
(2, "Not at all", 1),
(3, "Several days", 2),
(4, "More than half the days", 3),
(5, "Nearly everyday", 4),
]
vars = []
for r in range (2, 11):
var = tk.StringVar()
vars.append(var)
for c, text, b_val in MODES:
tk.Radiobutton(frame, text=text, variable=var, indicatoron=0, value=b_val, font=({}, 9), padx=100, pady=15, command=print_var).grid(padx=2, row=r, column=c, sticky='w')
var.trace('w', print_var)
I don't understand how I assign var to the variable, yet it becomes undefined later? I'm new to coding and I'm sure this is simple, but help would be appreciated.
Upvotes: 0
Views: 159
Reputation: 385820
It's hard to understand the code in the question, but I'm going to assume MODES
and the code following it are not inside print_var
.
var
is a temporary local variable which cannot be used outside of the loop (technically speaking it can, but it won't work the way you are thinking it will). However, it is added to the vars
list. If you make vars
global (or if it is global by virtual of running in the global scope), you can access it from other functions.
For example, to print the value of the first variable you can do this:
print(vars[0].get())
To print the value of all nine variables, you could do it like this:
def print_vars():
for variable in vars:
print(variable.get())
Upvotes: 1