Python tkinter radiobutton小部件,颜色不会改变

时间:2017-09-02 22:22:48

标签: python python-3.x tkinter

我正在lynda.com上学习Python GUI,出于某种原因,我的代码不起作用,而导师的代码完全正常。我将导师的工作复制到了我的代码中,但它仍然不起作用。

这是我的代码:

import tkinter as tk
from tkinter import ttk
win = tk.Tk()
win.title("Python GUI")

COLOR1 = "Blue"
COLOR2 = "Gold"
COLOR3 = "Red"

# Radiobutton Callback
def radCall():
    radSel = radVar.get()
    if   radSel == 1: win.configure(background=COLOR1)
    elif radsel == 2: win.configure(background=COLOR2)
    elif radsel == 3: win.configure(background=COLOR3)

# create three Radiobuttons using one variable
radVar = tk.IntVar()
rad1 = tk.Radiobutton(win, text=COLOR1, variable=radVar, value=1, command=radCall)
rad1.grid(column=0, row=5, sticky=tk.W, columnspan=3)

rad2 = tk.Radiobutton(win, text=COLOR2, variable=radVar, value=2, command=radCall)
rad2.grid(column=1, row=5, sticky=tk.W, columnspan=3)

rad3 = tk.Radiobutton(win, text=COLOR3, variable=radVar, value=3, command=radCall)
rad3.grid(column=2, row=5, sticky=tk.W, columnspan=3)

win.mainloop()

问题是,每当我点击蓝色无线电按钮时,它都可以工作,而金色和红色在我的终端上给我错误。

错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Joshua\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "radiobuttonwidget.py", line 60, in radCall
    elif radsel == 2: win.configure(background=COLOR2)
NameError: name 'radsel' is not defined

elif radsel == 3

相同

1 个答案:

答案 0 :(得分:0)

您已将变量定义为radSel,并且在循环中,您尝试使用radsel。改变" s"到" S"。这应该是问题所在。