python - 为 tkinter 小部件创建一个类来调用默认属性

标签 python class user-interface tkinter widget

我正在尝试使用 Python3 中的 tkinter 创建一个 GUI,它将有几个按钮,我不想每次都为所有按钮键入相同的属性,如下所示:

tkinter.Button(topFrame, font=("Ariel", 16), width=10, height=10,
               fg="#ffffff", bg="#000000", text="Cake")

例如,每个按钮上的fgbg颜色和大小都相同。每个按钮上唯一改变的是文本以及屏幕上放置它们的位置。

我对编程和 Python 很陌生,当我想创建一个新按钮时,我尝试重用代码。我认为我缺少对类(class)的一些理解,而当我阅读它时我没有得到这些理解。

我想为每个按钮和不同的框架传递不同的文本,以便将其放置在 GUI 上的不同位置,并使其他所有内容都相同。

到目前为止我的代码:

import tkinter
import tkinter.messagebox

window = tkinter.Tk()

#create default values for buttons
#frame and buttonText are the values passed to the class when making a new
#button
class myButtons:
     def buttonLayout(self, frame, buttonText):
          self.newButton=tkinter.Button(frame, font=("Ariel", 16),
                                        width=10, height=10, fg=#ffffff,
                                        bg=#000000, text=buttonText)

topFrame = tkinter.Frame(window)
topFrame.pack()

#create new button here and place in the frame called topFrame with the text
#"Cake" on it
buttonCake = myButtons.buttonLayout(topFrame, "Cake")
#position the new button in a certain cell using grid in topFrame
buttonCake.grid(row=1, column=0)

window.mainloop()

当我尝试运行它时出现的错误是:

TypeError: buttonLayout() missing 1 required positional argument: 'buttonText'

我很困惑,因为我传入了“Cake”,但错误表明它丢失了。

感谢您指出init,我不知道如何使用init来解决我的问题,但这以及这里给出的答案很有帮助。谢谢。

最佳答案

由于 self 参数,您会收到错误。 还有一个问题是您的代码未创建 MyButtons 类的实例。

以下示例继承自 Button 并自定义 __init__ 以设置一些默认值。

import tkinter
import tkinter.messagebox

window = tkinter.Tk()    

#create default values for buttons
#frame and buttonText are the values passed to the class when making a new button

class MyButton(tkinter.Button):
    def __init__(self, *args, **kwargs):
        if not kwargs:
            kwargs = dict()
        kwargs['font'] = ("Arial", 16)
        kwargs['width'] = 10,
        kwargs['height'] = 10,
        kwargs['fg'] = '#ffffff',
        kwargs['bg'] = '#000000',
        super().__init__(*args, **kwargs)

topFrame = tkinter.Frame(window)
topFrame.pack()

#create new button here and place in the frame called topFrame with the text "Cake" on it
buttonCake = MyButton(topFrame, text="Cake")
#position the new button in a certain cell using grid in topFrame
buttonCake.grid(row=1, column=0)

window.mainloop()

这会强制将默认值放入按钮中。仅当您不在调用中传递它们时,您才可以添加 if 语句来定义它们,方法如下:

if not 'width' in kwargs:
    kwargs['width'] = 10 

关于python - 为 tkinter 小部件创建一个类来调用默认属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55151133/

相关文章:

python - 如何强制 Django 的 urls.py 正则表达式仅限于 ASCII 数字?

python - 使用 defaultdict 处理动态插入键(如果不存在)

java - 理解Java中的内部类

c++ - 制作按钮并处理它们

python - 我可以使用 Django 模型对数据库执行复杂查询吗?

Java 类写在类括号之外

Swift - 父类中属性的默认值应该是什么?

multithreading - 如何使用线程获得稳定、快速的 UI?

java - JButtons 仅在 BorderLayout.CENTER 中出现在 JFrame 上,而不是在 SOUTH 或 NORTH 中

python - 无法在不转换为 ascii 的情况下拆分 unicode 字符串 - python 2.7