【发布时间】:2018-11-17 00:47:08
【问题描述】:
我正在尝试用 python 和 tkinter 编写我的第一个脚本。
当我点击按钮Validate时,我需要输入变量选择的每个复选框的名称时,我被阻止并且迷路了。
复选框在文本文件中是动态的。示例文件:
item1
item2
...
item100
GUI 屏幕:
这是我的代码:
(# 中的代码是我尝试过的,但没有成功。)
from tkinter import *
from tkinter.ttk import Frame, Label, Entry
import glob
class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.master.title("My Menu")
menubar = Menu(self.master)
self.master.config(menu=menubar)
fileMenu = Menu(menubar)
submenu = Menu(fileMenu)
submenu.add_command(label="lst1", command=self.onDisplay)
submenu.add_command(label="lst2")
submenu.add_command(label="lst3")
fileMenu.add_cascade(label='Listing', menu=submenu, underline=0)
fileMenu.add_separator()
fileMenu.add_command(label="Exit", underline=0, command=self.onExit)
menubar.add_cascade(label="File", underline=0, menu=fileMenu)
## Here the function which display checkboxes
def onDisplay(self):
self.pack(fill=BOTH, expand=True)
frame1 = Frame(self)
frame1.pack(fill=BOTH)
lbl1 = Label(frame1, text="Choice", width=6)
path = '/root/liste/*.txt'
files=glob.glob(path)
count = 0
#var = dict()
for file in files:
with open(file, 'r') as lst_file:
for item in lst_file:
#var[item]=IntVar()
#cb = Checkbutton(frame1, text=item.rstrip(), variable=var[item], command=self.cb)
##Here all checkboxes generated dynamically
cb = Checkbutton(frame1, text=item.rstrip())
cb.grid(row=count//10, column=count%10)
#cb.pack()
count += 1
#btn1 = Button(self, text='Validate', font=("Arial", 12), command=self.cb)
btn1 = Button(self, text='Validate', font=("Arial", 12))
btn1.pack(side=RIGHT, padx=5)
def cb(self):
print("variable is", self.var.get())
def onExit(self):
self.quit()
def main():
root = Tk()
root.geometry("800x550+300+300")
app = Example()
root.mainloop()
if __name__ == '__main__':
main()
【问题讨论】: