Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 特金特:制作';类别';用于按钮和标签_Python_Python 3.x_Tkinter - Fatal编程技术网

Python 特金特:制作';类别';用于按钮和标签

Python 特金特:制作';类别';用于按钮和标签,python,python-3.x,tkinter,Python,Python 3.x,Tkinter,所以,我在tkinter框架中有很多不同的按钮和标签,我都希望它们具有相似的属性。假设我希望它们的前景色都是红色,并且有一个透明的背景(我可以这样做吗?这个透明的背景只用于按钮。) 我可以为按钮设置一个类似css的类吗(我想这是在ttk中,但如果不是的话,它会更好),这样可以使我所有的按钮和标签都有红色文本?您可以扩展按钮类,并根据需要定义其属性。例如: from tkinter import * class MyButton(Button): def __init__(self,

所以,我在tkinter框架中有很多不同的按钮和标签,我都希望它们具有相似的属性。假设我希望它们的前景色都是红色,并且有一个透明的背景(我可以这样做吗?这个透明的背景只用于按钮。)


我可以为按钮设置一个类似css的
类吗(我想这是在ttk中,但如果不是的话,它会更好),这样可以使我所有的按钮和标签都有红色文本?

您可以扩展
按钮
类,并根据需要定义其属性。例如:

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()

哇!现在我看到了,我觉得很明显。谢谢但我在课堂上怎么做呢?我会做self.MyButton()?@Kevin但在类中做什么?打包按钮?如中所述,使其成为父类应用程序的子类,然后使应用程序具有MyButton()内容。对不起,我不太擅长这个。
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()