删除小部件(涉及tkinter模块)

时间:2011-11-25 13:25:29

标签: python tkinter

这里有新人,我慢慢得到了蟒蛇的一瞥,但我有一个问题。

我这里有两个文件

一个名为first_file.py

from other_file import GameFrame
from Tkinter import Tk

def main():
    tk = Tk()
    tk.title("Game of Life Simulator")
    tk.geometry("380x580")
    GameFrame(tk)
    tk.mainloop()
main()

,另一个是other_file.py

from Tkinter import *
from tkFileDialog import *

class GameFrame (Frame):
    def __init__(self, root):
        Frame.__init__(self,root)
        self.grid()
        self.mychosenattribute=8 
        self.create_widgets()

    def create_widgets(self):
        for rows in range(1,21):
            for columns in range(1,21):
                self.columns = columns
                self.rows = rows
                self.cell = Button(self, text='X')
                self.cell.bind("<Button-1>", self.toggle)
                self.cell.grid(row=self.rows, column=self.columns)

    reset = Button(self, text="Reset")
    reset.bind("<Button-1>", self.reset_button)
    reset.grid(row=22, column = 3, columnspan=5)

    def reset_button(self, event):
        self.cell.destroy()
        for rows in range(1,21):
               for columns in range(1,21):
                   self.columns = columns
                   self.rows = rows
                   self.cell = Button(self, text='')
                   self.cell.bind("<Button-1>", self.toggle)
                   self.cell.grid(row=self.rows, column=self.columns)

按下重置按钮后,现在发生的事情是一个按钮被破坏,另一组按钮在已经存在的按钮上面制作,但我需要能够销毁或至少将所有按钮配置为空白。那么,为了生成它们,我将如何为所有按钮执行此操作? (除了使用for循环之外,还有更好的方法来生成按钮吗?)谢谢。

1 个答案:

答案 0 :(得分:1)

常用方法是将对象保存在列表(或字典)中,以便在需要时访问它们。一个简单的例子:

self.mybuttons = defaultdict(list)
for rows in range(1,21):
    for columns in range(1,21):
        self.mybuttons[rows].append(Button(self, text=''))

然后你可以通过这种方式获得按钮:

abutton = self.mybuttons[arow][acolumn]

您的代码存在一些阻止运行它的问题(reset行的缩进以及未定义self.toggle的使用),所以我无法修复它,但这个示例应该足够了为你做。