我正在尝试将小部件存储在列表中以保存一些代码行。我当前的想法是将元素添加到数据类,将这些元素保存在列表中,然后遍历该列表以根据数据类中存储的信息创建小部件。
import tkinter as tk
from dataclasses import dataclass
@dataclass
class elemente():
name : str = "empty"
typ : str = "empty"
row : int = 0
col : int = 0
cmd : str = 'no command'
text : str = 'no Text'
class GUI(tk.Frame):
def __init__(self, master = None):
self.search_btn = elemente(typ='btn', text="search", row=0, col=2, cmd=self.test)
self.result_btn = elemente(typ='btn', text="results", row=3, col=2, cmd=self.test)
self.list_main = [self.search_btn, self.result_btn]
self.add_elements(self.list_main)
tk.Frame.__init__(self, master)
def add_elements(self, cur_list):
for elem in cur_list:
if elem.typ == 'btn':
elem = tk.Button(text = elem.text, command = elem.cmd)
elem.grid(row = elem.row, column = elem.col)
def test(self):
pass
root = tk.Tk()
gui = GUI(master = root)
gui.mainloop()
错误消息:
AttributeError:“按钮”对象没有属性“行”
通常,我将通过以下方式访问信息: self.search_btn.typ等有效。问题似乎出在将按钮存储在self.list_main中。有谁知道原因,还是有其他方法可以将许多按钮,文本小部件存储在列表中?
答案 0 :(得分:0)
您应该像下面这样添加自我:
def add_elements(self, cur_list):
for elem in cur_list:
if elem.typ == 'btn':
self.elem = tk.Button(text = elem.text, command = elem.cmd)
self.elem.grid(row = elem.row, column = elem.col)