删除小部件(涉及 tkinter 模块) [英] Deleting widgets (involving tkinter module)
问题描述
这里的新人,我正在慢慢掌握 Python 的窍门,但我有一个问题.
new guy here and I'm slowly getting the hang of python, but I have a question.
我这里有两个文件
一个名为 first_file.py
one is named 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
and the other is 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 循环来生成它们,我将如何对所有按钮执行此操作?(除了使用 for 循环之外,还有没有更好的方法来生成按钮?)谢谢.
After I push the reset button what happens right now is one button gets destroyed and another set of buttons are made on top of the already present buttons, but I need to be able to destroy or atleast configure all buttons to be blank. So how would I do that for all the buttons since I used a for loop to generate them? (Is there a better way to generate the buttons besides using a for loop?) Thanks.
推荐答案
一种常见的方法是将对象保存在列表(或字典)中,以便在需要时访问它们.一个简单的例子:
A common method is to save your objects in a list (or dictionary) in order to access them when needed. A simple example:
self.mybuttons = defaultdict(list)
for rows in range(1,21):
for columns in range(1,21):
self.mybuttons[rows].append(Button(self, text=''))
这样你就可以得到按钮了:
Then you can get buttons, this way:
abutton = self.mybuttons[arow][acolumn]
您的代码存在一些问题,无法运行它(reset
行的缩进和未定义的 self.toggle
的使用),所以我无法修复它,但这个例子应该足以让你做到.
There are some problems with your code that prevent running it (indentation of the reset
lines and the use of the undefined self.toggle
), so I could not fix it, but this example should be enough for you to do it.
这篇关于删除小部件(涉及 tkinter 模块)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!