Python表单:使用TKinter - >基于GUI中选中的复选框运行脚本 [英] Python Form: Using TKinter --> run script based on checked checkboxes in GUI

查看:639
本文介绍了Python表单:使用TKinter - >基于GUI中选中的复选框运行脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用tkinter(参见图片)在Python 3.5中创建了以下复选框弹出窗口,其中包含以下代码:

I have created the following checkbox popup in Python 3.5 using tkinter (see image) with the following code:

    from tkinter import *

    class Checkbar(Frame):
       def __init__(self, parent=None, picks=[], side=LEFT, anchor=W):
          Frame.__init__(self, parent)
          self.vars = []
          for pick in picks:
             var = IntVar()
             chk = Checkbutton(self, text=pick, variable=var)
             chk.pack(side=side, anchor=anchor, expand=YES)
             self.vars.append(var)
       def state(self):
          return map((lambda var: var.get()), self.vars)

    if __name__ == '__main__':
       root = Tk()
       lng = Checkbar(root, ['DerVar1', 'DerVar2', 'DerVar3', 'DerVar4', 'DerVar5', 'DerVar6', 'DerVar7', 'DerVar8'])
       tgl = Checkbar(root, ['DerVar9','DerVar10', 'DerVar11', 'DerVar12', 'DerVar13', 'DerVar14'])
       lng.pack(side=TOP,  fill=X)
       tgl.pack(side=LEFT)
       lng.config(relief=GROOVE, bd=2)

   def allstates(): 
      print(list(lng.state()), list(tgl.state()))
   Button(root, text='Quit', command=root.quit).pack(side=RIGHT)
   Button(root, text='Run', command=allstates).pack(side=RIGHT)
   root.mainloop()  

如你所见,我检查了'DerVar2'和DerVar3'。单击运行后,我将以黄色突出显示以下内容。

As you can see I have checked 'DerVar2' and DerVar3'. After I click run I get the following highlighted in yellow.

正如您所见,1对应于要检查的复选框。

As you can see a 1 corresponds to a checkbox getting checked.

变量'lng'是一个复选框对象。我想说如果检查'DerVar2',然后打印'test'但无法使其工作。

the variable 'lng' is a checkbar object. I want to say if 'DerVar2' is checked, then print 'test' but can't get it to work.

这是我试过的代码,下面是我得到的错误:

This is the code I have tried and below is the error I get:

if lng[1] == 1:
    print ('test')

TypeError:无法将'int'对象隐式转换为str

TypeError: Can't convert 'int' object to str implicitly

推荐答案

问题是你的 Checkbar 类没有 __ getitem __ 方法所以 lng [1] 将触发错误。要做 lng [1] == 1 而不出错,只需将以下方法添加到r Checkbar class:

The problem is that your Checkbar class has no __getitem__ method so lng[1] will trigger an error. To do lng[1] == 1 without errors, just add the following method to you rCheckbar class:

def __getitem__(self, key):
    return self.vars[key].get()

那样 lng [i] 将返回值i-th Checkbar的IntVar

That way lng[i] will return the value of the i-th IntVar of the Checkbar

这篇关于Python表单:使用TKinter - >基于GUI中选中的复选框运行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆