2013-04-29 50 views
2

我正在尝试使用python和tkinter来创建一个程序,该程序运行在复选框中选中的程序。从python tkinter的复选框中获取输入?

import sys 
from tkinter import * 
import tkinter.messagebox 
def runSelectedItems(): 
    if checkCmd == 0: 
     labelText = Label(text="It worked").pack() 
    else: 
     labelText = Label(text="Please select an item from the checklist below").pack() 

checkBox1 = Checkbutton(mGui, variable=checkCmd, onvalue=1, offvalue=0, text="Command Prompt").pack() 
buttonCmd = Button(mGui, text="Run Checked Items", command=runSelectedItems).pack() 

这是代码,但我不明白为什么它不工作?

谢谢。

+0

[获取Tkinter的复选框的状态]的可能重复(http://stackoverflow.com/questions/4236910/getting-tkinter-check-box-state) – 2014-01-15 09:27:35

回答

8

您需要使用一个IntVar的变量:

checkCmd = IntVar() 
checkCmd.set(0) 
def runSelectedItems(): 
    if checkCmd.get() == 0: 
     labelText = Label(text="It worked").pack() 
    else: 
     labelText = Label(text="Please select an item from the checklist below").pack() 

checkBox1 = Checkbutton(mGui, variable=checkCmd, onvalue=1, offvalue=0, text="Command Prompt").pack() 
buttonCmd = Button(mGui, text="Run Checked Items", command=runSelectedItems).pack() 

在其他新闻中,成语:

widget = TkinterWidget(...).pack() 

是不是一个很好的一个。在这种情况下,widget始终为None,因为这是由Widget.pack()返回的内容。一般来说,你应该创建你的小部件,并通过2个独立的步骤让它知道几何管理器。例如: -

checkBox1 = Checkbutton(mGui, variable=checkCmd, onvalue=1, offvalue=0, text="Command Prompt") 
checkBox1.pack() 
相关问题