删除小部件(涉及tkinter模块)
我刚开始学习Python,有些问题想请教大家。
我这里有两个文件:
一个叫做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)
当我按下重置按钮时,现在的情况是一个按钮被销毁了,另外一组按钮又在已经存在的按钮上面生成了。但我希望能把所有按钮都销毁,或者至少把它们的内容清空。那么我该怎么做呢?因为我用循环生成了这些按钮。(有没有更好的方法来生成按钮,而不是用循环呢?)谢谢大家。
1 个回答
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
),所以我无法帮你修复,但这个例子应该足够让你自己去解决了。