使用面向对象编程和tkinter显示标签和按钮



我将用面向对象的方法编写一个包含许多标签和按钮的程序。假设我想创建的程序是这样的:

p1 = Label(root, bg='lightblue')
p1.place(relwidth=1, relheight=0.5)
p1 = Button(root, text= 'test')
p1.place(x= 0, y= 0)
p2 = Label(root, bg='red')
p2.place(y=200, relwidth=1, relheight=0.5)
p2 = Button(root, text= 'test 2')
p2.place(x= 0, y= 200)

为了使p3, p4, p5等更有效,我写了以下内容:

from tkinter import *
root = Tk()
canvas = Canvas(height=400, width=400)
canvas.pack()
class Display:
def __init__(self, root, x, y, bg, relwidth, relheight, text):
self.root = root
self.x = x
self.y = y
self.bg = bg
self.relwidth = relwidth
self.relheight = relheight
self.text = text
def DisplayLabel(self):
Label(self.root, self.bg).pack(self.relwidth, self.relheight)
def DisplayButton(self):
Button(self.root, self.text).pack(self.x, self.y)

p1 = Display(root, 0, 0, 'lightblue', 1, 0.5, 'test')
p2 = Display(root, 0, 200, 'red', 1, 0.5, 'test 2')
p1.DisplayLabel()
p1.DisplayButton()
p2.DisplayLabel()
p2.DisplayButton()
root.resizable(False, False)
root.mainloop()

的想法是,而不是写每一个标签和按钮一遍又一遍我只是写我想要的值像p1和p2。代码大部分像预期的那样工作,我能够打印p1和p2的单独值。但是当我试图在程序中显示标签和按钮时,一切都出错了。当我尝试这部分时:

p1.DisplayLabel()
p1.DisplayButton()
p2.DisplayLabel()
p2.DisplayButton()

显示如下错误:

Traceback (most recent call last):
File "C:UsersDanielPycharmProjectsstockalarmtest.py", line 36, in <module>
p1.DisplayLabel()
File "C:UsersDanielPycharmProjectsstockalarmtest.py", line 27, in DisplayLabel
Label(self.root, self.bg).pack(self.relwidth, self.relheight)
File "C:UsersDanielAppDataLocalProgramsPythonPython39libtkinter__init__.py", line 3144, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:UsersDanielAppDataLocalProgramsPythonPython39libtkinter__init__.py", line 2565, in __init__
classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)]
AttributeError: 'str' object has no attribute 'items'

我做错了什么?如何在程序中显示按钮和标签?

您忘记指定您的实参应该设置哪些形参,就像您在第一个代码片段中所做的那样:

p1 = Label(root, bg='lightblue')
p1.place(relwidth=1, relheight=0.5)

然而,在第二个代码片段中,您只是在没有任何说明的情况下将变量放在那里:

Label(self.root, self.bg).pack(self.relwidth, self.relheight)
...
Button(self.root, self.text).pack(self.x, self.y)

应该是:

Label(self.root, bg = self.bg).place(relwidth = self.relwidth, relheight = self.relheight)
...
Button(self.root, text = self.text).place(x = self.x, y = self.y)

您还不小心把place写成了pack