首页 > 解决方案 > 使用继承正确扩展 tkinter 小部件

问题描述

我对 python 类有点陌生,我还不知道如何处理它们,我保证我已经做了一些研究来解决这个问题,但仍然不知道如何解决。所以,这里是:

我正在尝试使用 python 类来定义 tkinter 小部件,以便我可以相当快地实现它们。这一切都适用于按钮和标签,但我无法通过条目获得它。我将向您展示我是如何编写按钮和标签的,以说明我也尝试对条目做些什么(如果有必要,也许你们可以帮助我改进这一点?)。

class buttonStatic:
    def __init__(self, parent, row, col,rowspan, text, font, bg, fg, bd,width=None, function=None,sticky=None):
        button = tk.Button(parent, text=text, font=(font), bg=bg, fg=fg,bd=bd, width=width, command=function)
        button.grid(row=row, column=col,rowspan=rowspan, padx=padx, pady=pady, sticky=sticky)

class buttonDinamic:
    def __init__(self, parent, row, col,rowspan, textVar, font, bg, fg,bd,width=None, function=None,sticky=None):
        variable = tk.StringVar()
        variable.set(textVar)
        button = tk.Button(parent, textvariable=variable, font=(font), bg=bg, fg=fg,bd=bd, width=width, command=function)
        button.grid(row=row, column=col,rowspan=rowspan, padx=padx, pady=pady, sticky=sticky)


class labelStatic:
    def __init__(self, parent, row, col, text, font, bg, fg, sticky=None):
        label = tk.Label(parent, text=text, font=(font), bg=bg, fg=fg)
        label.grid(row=row, column=col, padx=padx, pady=pady, sticky=sticky)


class labelDinamic:
    def __init__(self, parent, row, col, textVar, font, bg, fg, sticky=None):
        variable = tk.StringVar()
        variable.set(textVar)
        label = tk.Label(parent, textvariable=variable, font=(font), bg=bg, fg=fg)
        label.grid(row=row, column=col, padx=padx, pady=pady, sticky=sticky)

现在,这就是我为条目编码的内容,遵循这个答案我添加了一些 lambda 函数以使其“可重用”)

def focusIn(entry):
    entry.delete(0,'end')
    entry.config(fg=fColor_1)
    return

def focusOut(entry):
    entry.delete(0,'end')
    entry.config(fg=fColor_3)
    entry.insert(0,'Presupuesto')
    return

def enter(entry):
    x = entry.get()
    print(entry.get())
    focusOut(entry)
    return

testEntry = tk.Entry(module,bg=bgColor_1,width = 30, fg='grey')
testEntry.grid(row=0,column = 1)
testEntry.insert(0,'Presupuesto')
testEntry.bind('<FocusIn>',lambda x: focusIn(testEntry))
testEntry.bind('<FocusOut>',lambda x: focusIn(testEntry))
testEntry.bind('<Return>',lambda x: enter(testEntry))

这是我的实际问题

如何制作成一个类,以及在将小部件制作成一个类时如何使用.get()和方法?.set()

由于我在 python 类方面不是很有经验(尤其是将它们与 tkinter 结合使用),我什至不知道我要问的是否可能!pd:对不起,如果我的英语不是很好,那不是我的母语

标签: pythonclassooptkinter

解决方案


问题:如何class从a变成自己的tkinter.Entry

这叫继承。
全部。继承的方法,例如.get()行为相同。

class MyEntry(tk.Entry):
    def __init__(self, parent, **kwargs):
        # Defaults
        kwargs['fg'] = 'grey'
        super().__init__(parent, **kwargs)

        self.bind('<FocusIn>', self.on_event)
        self.bind('<FocusOut>', self.on_event)
        self.bind('<Return>', self.on_event)

    def on_event(self, event):
        print('on_event type:{}'.format(event.type))

用法

testEntry = MyEntry(module, bg=bgColor_1, width = 30)
testEntry.grid(row=0,column = 1)
testEntry.insert(0,'Presupuesto')

print(testEntry.get())

推荐阅读