在复选框中将所选选项显示到下一个tkinter窗口中的新列表

时间:2017-10-14 12:17:02

标签: python tkinter ubuntu-16.04

我想在新Tkinter窗口的新列表中显示我的复选框列表中的所选选项,并在浏览时返回到主屏幕 (使用带有Ubuntu 16.04的Python 3.5)。

import tkinter as tk
import tkMessageBox

lista=['jpeg','jfit','tiff','gif','png','bmp']    
class PopUp(tk.Toplevel):
    def __init__(self, number=10):
        tk.Toplevel.__init__(self)

        self.global_state = tk.BooleanVar()

        cb = tk.Checkbutton(self, text="select/deselect all", variable=self.global_state, command=self.select_clear_states)
        cb.grid(row=0, column=0, padx=5, pady=1)

        self.states = []

        for n in range(len(lista)):
            var = tk.BooleanVar()
            cb = tk.Checkbutton(self, text=str(lista[n]), variable=var)
            cb.grid(row=n+1, column=0, padx=5, pady=1)
            self.states.append(var)

    def select_clear_states(self):
        state = self.global_state.get()
        for x in self.states:
            x.set(state)

def popup(num):
    win = PopUp(num)

root = tk.Tk()

b = tk.Button(root, text="5 checkboxes", command=lambda:popup(5))
b.pack()

root.mainloop()

1 个答案:

答案 0 :(得分:0)

假设我理解正确,如果您想使用Checkbutton执行此操作,则可以执行以下操作:

from tkinter import *

class App:
    def __init__(self, root):
        self.root = root
        self.top = Toplevel(root)
        self.frame = Frame(self.top)
        self.frame.pack()
        self.check = []
        self.var = []
        for i in range(10):
            self.var.append(IntVar())
            self.var[i].trace("w", self.callback)
            self.check.append(Checkbutton(self.root, text="Option "+str(i), variable=self.var[i]))
            self.check[i].pack()
    def callback(self, *args):
        self.frame.destroy()
        self.frame = Frame(self.top)
        self.frame.pack()
        for i, c in zip(self.check, self.var):
            if c.get() == 1:
                Label(self.frame, text=i.cget("text")).pack()

root = Tk()
App(root)
root.mainloop()

或者你可能会发现Listbox完成你想要的东西,而且(IMO)看起来更干净,更友好:

from tkinter import *

class App:
    def __init__(self, root):
        self.root = root
        self.listbox = Listbox(self.root, selectmode=MULTIPLE)
        self.listbox.pack()
        for i in range(10):
            self.listbox.insert(END, "Option "+str(i))

root = Tk()
App(root)
root.mainloop()

使用Listbox你可能甚至不需要两个窗口,因为选择通过突出显示它们可以清楚地显示选择了哪些选项。