python tkinter输入框_从python tkinter中的复选框获取输入?

这篇博客讲述了如何利用Python的Tkinter库创建一个带有复选框的图形用户界面,用户可以从中选择要运行的程序。问题在于原始代码中变量checkCmd未正确初始化,导致无法正确检查复选框的状态。解决方案是使用IntVar()来初始化checkCmd,并通过checkCmd.get()检查其值,以决定是否显示相应的标签。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

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.

解决方案

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值