从python tkinter中的Checkbox获取输入?

use*_*101 7 python checkbox tkinter input

我正在尝试使用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()
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

mgi*_*son 11

您需要使用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()
Run Code Online (Sandbox Code Playgroud)

在其他新闻中,成语:

widget = TkinterWidget(...).pack()
Run Code Online (Sandbox Code Playgroud)

不是一个很好的.在这种情况下,widget永远是None因为那是由返回的Widget.pack().通常,您应该创建窗口小部件,并通过2个单独的步骤使其了解几何管理器.例如:

checkBox1 = Checkbutton(mGui, variable=checkCmd, onvalue=1, offvalue=0, text="Command  Prompt")
checkBox1.pack()
Run Code Online (Sandbox Code Playgroud)