2013-04-29 51 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() 
相關問題