2017-02-28 87 views
-1

我有这个python script.I找不到我犯了什么错误。任何人都可以告诉我我在这个程序中犯了什么错误?python tkinter Radiobutton

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

什么是你的计划的目标是什么? –

+0

我想在每个问题后打印标签“写/错”..但它不打印当我点击单选按钮 – Satish17

+1

为什么你认为单选按钮知道单击时要调用哪个函数? –

回答

0

提供的源代码是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

在每个Radiobutton更改时调用函数sel()。如果没有选择 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用于显示的第一个问题的“正确/错误”,并显示了第二个问题。

重命名sel()功能的第二l2lQ2以防止改变。

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)