Tkinter:为按钮和标签创建“类”

2 投票
2 回答
7498 浏览
提问于 2025-04-18 08:39

我在一个tkinter的框架里有很多不同的按钮和标签,我希望它们都有相似的属性。比如说,我想让它们的文字颜色都是红色,背景是透明的(按钮的背景可以透明吗?)。

我能不能为按钮创建一个class(我觉得这是在ttk里,不过如果不是ttk就更好了),就像css那样,让我所有的按钮和标签都显示红色的文字?

2 个回答

0

在编程中,有时候我们会遇到一些问题,特别是在使用某些工具或库的时候。比如,有人可能会问,为什么在使用某个特定的功能时,结果和预期的不一样。这种情况可能是因为我们对这个功能的理解不够深入,或者是使用的方法不太正确。

在这种情况下,查看相关的文档或者社区的讨论是非常有帮助的。文档通常会详细解释每个功能的用法和注意事项,而社区的讨论则可以提供其他人的经验和解决方案。

另外,调试也是一个很重要的步骤。通过逐步检查代码,看看每一步的输出结果,可以帮助我们找到问题的根源。记住,编程是一个不断学习和解决问题的过程,不要害怕犯错,重要的是从中吸取经验。

from tkinter import *

class My_Button(Button):
    def __init__(self, text, row, col, command, color=None, **kwargs):
        self.text = text
        self.row = row
        self.column = col
        self.command = command
        self.color = color
        super().__init__()
        self['bg'] = self.color
        self['text'] = self.text
        self['command'] = self.command
        self.grid(row=self.row, column=self.column)


def dothings():
    print('Button class worked')

window = Tk()
window.title("Test Button Class")
window.geometry('400x200')

btn1 = My_Button("Click Me", 0, 0, dothings, 'green')

window.mainloop()
8

你可以扩展(也就是增加功能)Button这个类,并根据自己的需要来定义它的属性。比如说:

from tkinter import *


class MyButton(Button):

    def __init__(self, *args, **kwargs):
        Button.__init__(self, *args, **kwargs)
        self['bg'] = 'red'



root = Tk()
root.geometry('200x200')

my_button = MyButton(root, text='red button')
my_button.pack()

root.mainloop()

enter image description here

撰写回答