【问题标题】:How to save tkinter widgets with dataclass in a list?如何在列表中保存带有数据类的 tkinter 小部件?
【发布时间】:2019-12-03 11:00:12
【问题描述】:

我正在尝试将小部件存储在列表中以节省一些代码行。我目前的想法是将元素添加到数据类中,将这些元素保存在一个列表中,然后遍历该列表以根据数据类中存储的信息创建小部件。

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: 'Button' 对象没有属性 'row'

通常我会通过以下方式访问信息: self.search_btn.typ 等确实有效。问题似乎在于将按钮存储在 self.list_main 中。有谁知道这是什么原因,或者是否有不同的方法可以在列表中存储许多按钮、文本小部件?

【问题讨论】:

  • 你用对象Button(...覆盖elem = ,重命名为button = tk.Button(...
  • 你是对的。它正在覆盖它。只需使用 elem.name 而不是 elem 作为名称即可解决问题。

标签: python list tkinter widget


【解决方案1】:

你应该像下面这样添加到自己:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    • 2016-08-19
    • 1970-01-01
    相关资源
    最近更新 更多