Get the input from a Checkbox in python tkinter?

2019-06-22 07:55发布

I am trying to use python and tkinter to make a program that run programs that have been selected in a check box.

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.

1条回答
在下西门庆
2楼-- · 2019-06-22 08:49

You need to use an IntVar for the variable:

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, widget will always be None since 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.:

checkBox1 = Checkbutton(mGui, variable=checkCmd, onvalue=1, offvalue=0, text="Command  Prompt")
checkBox1.pack()
查看更多
登录 后发表回答