0
我想將Button的子類化爲OPButtun。 OPButton是一個常規的Button,當鼠標懸停時可以編寫幫助消息。 OPButton必須接受任何可能的參數列表THRE常規按鈕構造函數會接受,加上兩個我自己的:消息和STRINGVAR哪裏把它寫在Tkinter:使用附加參數創建子類化按鈕
這是我的代碼(據說可運行)
from tkinter import *
from tkinter import ttk
class OPButton(Button):
""" """
def ___init___(self, parent, string, message, *args, **kwargs):
ttk.Button.__init__(self, parent, *args, **kwargs)
self.bind("<Enter>", command=lambda e: string.set(message))
self.bind("<Leave>", command=lambda e: string.set(""))
if __name__ == '__main__':
root = Tk()
root.str= StringVar()
OPButton(root, root.str, "hovering the button", text="click here").pack()
ttk.Label(root, textvariable=root.str).pack()
root.mainloop()
。
和錯誤消息:
Traceback (most recent call last):
File "C:\Users\planchoo\oPButton.py", line 19, in <module>
OPButton(root, "Hello World", "Bouton", text="Hello").pack()
TypeError: __init__() takes from 1 to 3 positional arguments but 4 were given
編輯:下面是Bryan的響應之後將校正的代碼。完美工作(謝謝)。
from tkinter import *
from tkinter import ttk
class OPButton(Button):
""" """
def __init__(self, parent, string, message, *args, **kwargs):
ttk.Button.__init__(self, parent, *args, **kwargs)
self.bind("<Enter>", lambda e: string.set(message))
self.bind("<Leave>", lambda e: string.set(""))
if __name__ == '__main__':
root = Tk()
root.chaine = StringVar()
OPButton(root, root.chaine, "Bouton", text="Hello").pack()
ttk.Label(root, textvariable=root.chaine).pack()
root.mainloop()
謝謝。我沒有找到正確的方向。我在原帖的末尾發佈了調試過的代碼。再次感謝。雖然錯誤是一個微不足道的錯字,但我被困了好幾個小時。 – quickbug
@quickbug沒問題。 :) –