【问题标题】:python tkinter Radiobuttonpython tkinter 单选按钮
【发布时间】:2017-02-28 17:56:11
【问题描述】:

我有这个 python 脚本。我找不到我犯了什么错误。谁能告诉我我在这个程序中犯了什么错误?

from tkinter import *
root=Tk()
v=IntVar()
s=IntVar()
def sel():
 x=v.get()
 if x==1:
    l2.config(text="correct")
 else:
    l2.config(text="wrong")
  z=s.get()
  if z==1:
    l3.config(text="correct")

 else:
    l3.config(text="wrong")
l=Label(root,text="what is 2 + 2 ?")
l.pack(anchor=W)
R1=Radiobutton(root,text="4",variable=v,value=1)
R1.pack(anchor=W)
R2=Radiobutton(root,text="5",variable=v,value=2)
R2.pack(anchor=W)
l2=Label(root)
l2.pack()
l2=Label(root,text="what is 5 + 9?")
l2.pack(anchor=W)
R3=Radiobutton(root,text="14",variable=s,value=1)
R3.pack(anchor=W)
R4=Radiobutton(root,text="5",variable=s,value=2)
R4.pack(anchor=W)
l3=Label(root)
l3.pack()
root.mainloop()

【问题讨论】:

  • 你的计划目标是什么?
  • 我想在每个问题之后打印在标签“写/错误”上..但是当我点击单选按钮时它不打印
  • 为什么单选按钮在被点击时知道调用哪个函数?

标签: python-2.7 python-3.x tkinter


【解决方案1】:

提供的源代码缺少Radiobutton 和管理选定Radiobutton 的函数sel() 之间的链接。其他误解和错误声明阻碍了“正确/错误”的显示。

错误1 - 管理Radiobutton的变化,每个控件都需要与检查功能联动。

要调用函数sel(),请在每个Radiobutton 上添加command

R1=Radiobutton(root,text="4",variable=v,value=1,command = lambda : sel())
...
R2=Radiobutton(root,text="5",variable=v,value=2,command = lambda : sel())
...
R3=Radiobutton(root,text="14",variable=s,value=1,command = lambda : sel())
...
R4=Radiobutton(root,text="5",variable=s,value=2,command = lambda : sel())

错误 2 - 在 sel() 函数中,检查 value 而不是使用简单的 if-else

函数sel() 在每次Radiobutton 更改时被调用。如果不 Radiobutton被选中,InVar()的返回值为0

def sel():
    x=v.get()
    if x==1: # value of R1
        l2.config(text="correct")
    elif x==2: # value of R2
        l2.config(text="wrong")
    z=s.get()
    if z==1: # value of R3
        l3.config(text="correct")
    elif z==2: # value of R4
        l3.config(text="wrong")

错误 3 - 变量 l2 用于显示第一个问题的“正确/错误”并显示第二个问题。

将第二个l2 重命名为lQ2 以防止更改sel() 函数。

R2=Radiobutton(root,text="5",variable=v,value=2,command = lambda : sel())
R2.pack(anchor=W)
l2=Label(root)
l2.pack()
lQ2=Label(root,text="what is 5 + 9?")
lQ2.pack(anchor=W)
R3=Radiobutton(root,text="14",variable=s,value=1,command = lambda : sel())
R3.pack(anchor=W)

【讨论】:

    猜你喜欢
    • 2016-09-11
    • 1970-01-01
    • 2014-03-16
    • 2016-09-01
    • 2016-06-10
    • 2021-06-09
    • 1970-01-01
    • 2012-12-02
    • 2015-09-11
    相关资源
    最近更新 更多