从python tkinter中的复选框获取输入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16285056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the input from a Checkbox in python tkinter?
提问by user2333101
I am trying to use python and tkinter to make a program that run programs that have been selected in a check box.
我正在尝试使用 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()
That is the code but I don't understand why it doesn't work?
那是代码,但我不明白为什么它不起作用?
Thanks.
谢谢。
回答by mgilson
You need to use an IntVarfor the variable:
您需要对IntVar变量使用 an :
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()
In other news, the idiom:
在其他新闻中,成语:
widget = TkinterWidget(...).pack()
Is not a very good one. In this case, widgetwill always be Nonesince that is what is returned by Widget.pack(). In general, you should create your widget and make it aware of the geometry manager in 2 separate steps. e.g.:
不是一个很好的。在这种情况下,widget将始终是,None因为那是Widget.pack(). 通常,您应该通过 2 个单独的步骤创建小部件并使其了解几何管理器。例如:
checkBox1 = Checkbutton(mGui, variable=checkCmd, onvalue=1, offvalue=0, text="Command Prompt")
checkBox1.pack()

