python在mainloop结束后获取checkbutton值

时间:2016-04-14 19:04:25

标签: python tkinter

我想知道,应用程序关闭后检查了哪些检查按钮。 如果我在任何集合中保存了checkbuttons值,则在销毁应用程序后无法访问该集合。

app = Application(path_to_files)
app.initialize(data)
app.mainloop()
#i want to know all checkbuttons values on this line 

checkerGUI.py

import Tkinter as tk
import tkFont
import webbrowser
import os
from PIL import ImageTk, Image
import ctypes

class Application(tk.Frame):

    def __init__(self, pwd="", master=None):
        tk.Frame.__init__(self, master)
        self.initImages(pwd)
        self.master.resizable(width=False, height=False)
        self.index = 0
        self.master.bind("<Return>", self.close)
        self.grid()
        self.games = []
        self.gamesHiddenFlags = {}

    def close(self, event):
        self.master.destroy()

    def getGamesHiddenFlags(self):
        return self.gamesHiddenFlags

    def initialize(self, games):
        self.games = games
        for game in self.games:
            self.gamesHiddenFlags[game.name] = tk.BooleanVar()
            self.createWidgetsFromGame(game, self.gamesHiddenFlags[game.name])

    def initImages(self, path):
        self.images = {}
        buf = Image.open(os.path.join(path, "images", "Classic.png"))
        buf = buf.resize((20, 20), Image.ANTIALIAS)  # The (250, 250) is (height, width)
        self.images['Classic'] = ImageTk.PhotoImage(buf)

        buf = Image.open(os.path.join(path, "images", "Jeopardy.png"))
        buf = buf.resize((20, 20), Image.ANTIALIAS)
        self.images['Jeopardy'] = ImageTk.PhotoImage(buf)

        buf = Image.open(os.path.join(path, "images", "On-site.png"))
        buf = buf.resize((20, 20), Image.ANTIALIAS)
        self.images['On-site'] = ImageTk.PhotoImage(buf)

        buf = Image.open(os.path.join(path, "images", "On-line.png"))
        buf = buf.resize((20, 20), Image.ANTIALIAS)
        self.images['On-line'] = ImageTk.PhotoImage(buf)

    def google_link_callback(event, site):
        webbrowser.open_new(site)

    def ShowImages(self, frame_in, type_img, place_img):
        type_img = type_img.replace("Attack-Defense", "Classic").replace("Attack", "Classic")
        type_img = type_img.replace("Hack quest", "Jeopardy")
        label = tk.Label(frame_in, image=self.images[type_img])
        label.pack(side="right")

        label = tk.Label(frame_in, image=self.images[place_img])
        label.pack(side="right")

    def createWidgetsFromGame(self, game, flag):
        frame = tk.Frame(self, relief='sunken')
        frame.grid(row=0, column=self.index, sticky="WN")
        frame_in = tk.Frame(frame)
        frame_in.grid(row=0, sticky="WE", column=self.index)

        header = tk.Label(frame_in, anchor="nw", justify="left", text="Игра: ")
        header.pack(expand=True, fill="x", side="left")

        self.ShowImages(frame_in, game.type, game.place_type)

        header = tk.Label(frame, anchor="nw", justify="left", text="Состояние: ")
        header.grid(row=1, sticky="WE", column=self.index)

        header = tk.Label(frame, anchor='nw', justify="left", text="Дата проведения: ", height=2)
        header.grid(row=3, sticky="WEN", column=self.index)

        header = tk.Label(frame, anchor="nw", justify="left", text="Продолжительность: ")
        header.grid(row=5, sticky="WE", column=self.index)

        header = tk.Label(frame, anchor="nw", justify="left", text="Сайт игры: ")
        header.grid(row=6, sticky="WE", column=self.index)

        header = tk.Label(frame, anchor="nw", justify="left", text="Ранг: ")
        header.grid(row=7, sticky="WE", column=self.index)

        header = tk.Checkbutton(frame, text="Не показывать: ", variable=flag)  # There is variable
        header.grid(row=8, sticky="WE", column=self.index)

        self.index += 1

        frame2 = tk.Frame(self, relief='sunken')
        frame2.grid(row=0, column=self.index, sticky="WN")

        header = tk.Label(frame2, anchor="nw", justify="left", text=game.name)
        header.grid(row=0, sticky="WE", column=self.index)

        header = tk.Label(frame2, anchor="nw", justify="left", text=game.state)
        header.grid(row=1, sticky="WE", column=self.index)

        header = tk.Label(frame2, anchor="nw", justify="left", text=game.date['start'].strftime("с %d %B в %H:%M"))
        header.grid(row=2, sticky="WE", column=self.index)

        header = tk.Label(frame2, anchor="nw", justify="left", text=game.date['end'].strftime("до %d %B в %H:%M"))
        header.grid(row=3, sticky="WE", column=self.index)

        header = tk.Label(frame2, anchor="nw", justify="left", text="%d дней %d часов" % (game.duration['days'], game.duration['hours']))
        header.grid(row=4, sticky="WE", column=self.index)

        header = tk.Label(frame2, anchor="nw", justify="left", fg='blue', font=tkFont.Font(underline=1, size=10), cursor="hand2", text=game.site)
        header.bind("<Button-1>", lambda e: self.google_link_callback(game.site))
        header.grid(row=5, sticky="WE", column=self.index)

        header = tk.Label(frame2, anchor="nw", justify="left", text=game.rank)
        header.grid(row=6, sticky="WE", column=self.index)

        self.index += 1

1 个答案:

答案 0 :(得分:1)

好的,我稍微修改了你的代码。您将在代码中找到解释作为注释。 我添加了协议方法(您可以使用self.master.protocol调用)并更改了close方法,以便在它销毁应用程序之前,它会遍历检查按钮并收集目录中的标志,然后将其转换为全局名单。

为了测试它,我必须注释掉代码的图像部分并创建我自己的游戏类以获得假游戏列表。
不知道我的解决方案是否优雅,但在我的测试条件下它是有效的。

所以在app.mainloop()尝试print(out)后,会给你一个零和一个列表。

希望它有所帮助。 啊,请检查一下!当我粘贴我的代码时,这个编辑器在这里做了一些奇怪的事情。


import Tkinter as tk
import tkFont
import webbrowser
import os
from PIL import ImageTk, Image
import ctypes

class Application(tk.Frame):

def __init__(self, pwd="", master=None): tk.Frame.__init__(self, master) self.initImages(pwd) self.master.resizable(width=False, height=False) self.index = 0 self.master.bind("<Return>", self.close_by_keyboard)#changed self.master.protocol("WM_DELETE_WINDOW", self.close_by_mouse)#added self.grid() self.games = [] self.gamesHiddenFlags = {} self.flags = {} #collection of flags global out #variable will exist after Application object is destroyed out = [] #List of flags for later use #get the variable and exit in case you are closing with a mouse click: def close_by_mouse(self): self.get_variables() self.master.destroy() #same as above for closing with return key: def close_by_keyboard(self, event): self.get_variables() self.master.destroy() def get_variables(self): for i in self.flags: out.append(self.flags[i].get()) def getGamesHiddenFlags(self): return self.gamesHiddenFlags def initialize(self, games): self.games = games for game in self.games: self.gamesHiddenFlags[game.name] = tk.BooleanVar() self.createWidgetsFromGame(game, self.gamesHiddenFlags[game.name]) def initImages(self, path): self.images = {} buf = Image.open(os.path.join(path, "images", "Classic.png")) buf = buf.resize((20, 20), Image.ANTIALIAS) # The (250, 250) is (height, width) self.images['Classic'] = ImageTk.PhotoImage(buf) buf = Image.open(os.path.join(path, "images", "Jeopardy.png")) buf = buf.resize((20, 20), Image.ANTIALIAS) self.images['Jeopardy'] = ImageTk.PhotoImage(buf) buf = Image.open(os.path.join(path, "images", "On-site.png")) buf = buf.resize((20, 20), Image.ANTIALIAS) self.images['On-site'] = ImageTk.PhotoImage(buf) buf = Image.open(os.path.join(path, "images", "On-line.png")) buf = buf.resize((20, 20), Image.ANTIALIAS) self.images['On-line'] = ImageTk.PhotoImage(buf) def google_link_callback(event, site): webbrowser.open_new(site) def ShowImages(self, frame_in, type_img, place_img): type_img = type_img.replace("Attack-Defense", "Classic").replace("Attack", "Classic") type_img = type_img.replace("Hack quest", "Jeopardy") label = tk.Label(frame_in, image=self.images[type_img]) label.pack(side="right") label = tk.Label(frame_in, image=self.images[place_img]) label.pack(side="right") def createWidgetsFromGame(self, game, flag): frame = tk.Frame(self, relief='sunken') frame.grid(row=0, column=self.index, sticky="WN") frame_in = tk.Frame(frame) frame_in.grid(row=0, sticky="WE", column=self.index) header = tk.Label(frame_in, anchor="nw", justify="left", text="Игра: ") header.pack(expand=True, fill="x", side="left") self.ShowImages(frame_in, game.type, game.place_type) header = tk.Label(frame, anchor="nw", justify="left", text="Состояние: ") header.grid(row=1, sticky="WE", column=self.index) header = tk.Label(frame, anchor='nw', justify="left", text="Дата проведения: ", height=2) header.grid(row=3, sticky="WEN", column=self.index) header = tk.Label(frame, anchor="nw", justify="left", text="Продолжительность: ") header.grid(row=5, sticky="WE", column=self.index) header = tk.Label(frame, anchor="nw", justify="left", text="Сайт игры: ") header.grid(row=6, sticky="WE", column=self.index) header = tk.Label(frame, anchor="nw", justify="left", text="Ранг: ") header.grid(row=7, sticky="WE", column=self.index) self.flags[self.index]=tk.IntVar() header = tk.Checkbutton(frame, text="Не показывать: ", variable=self.flags[self.index]) # There is variable header.grid(row=8, sticky="WE", column=self.index) self.index += 1 frame2 = tk.Frame(self, relief='sunken') frame2.grid(row=0, column=self.index, sticky="WN") header = tk.Label(frame2, anchor="nw", justify="left", text=game.name) header.grid(row=0, sticky="WE", column=self.index) header = tk.Label(frame2, anchor="nw", justify="left", text=game.state) header.grid(row=1, sticky="WE", column=self.index) header = tk.Label(frame2, anchor="nw", justify="left", text=game.date['start'].strftime("с %d %B в %H:%M")) header.grid(row=2, sticky="WE", column=self.index) header = tk.Label(frame2, anchor="nw", justify="left", text=game.date['end'].strftime("до %d %B в %H:%M")) header.grid(row=3, sticky="WE", column=self.index) header = tk.Label(frame2, anchor="nw", justify="left", text="%d дней %d часов" % (game.duration['days'], game.duration['hours'])) header.grid(row=4, sticky="WE", column=self.index) header = tk.Label(frame2, anchor="nw", justify="left", fg='blue', font=tkFont.Font(underline=1, size=10), cursor="hand2", text=game.site) header.bind("<Button-1>", lambda e: self.google_link_callback(game.site)) header.grid(row=5, sticky="WE", column=self.index) header = tk.Label(frame2, anchor="nw", justify="left", text=game.rank) header.grid(row=6, sticky="WE", column=self.index) self.index += 1</pre></code>