1 回答

TA貢獻2003條經驗 獲得超2個贊
問題:從小tkinter部件繼承
使用從小tkinter.Button部件繼承的您自己的小部件對象。
而不是重復常見的參數,如:
self.one = Button(master,
text="1",
command=self.one,
bg="red", bd=8,
height=2,
width=10,
activebackground="blue")
self.one.place(relx=0.6,
rely=0.9)
定義您自己的class MyButton,它定義了類內部的所有公共參數Button。
class MyButton(tk.Button):
def __init__(self, parent, relx, rely, **kwargs):
super().__init__(parent, kwargs,
bg="red", bd=8, height=2, width=10, activebackground="blue")
self.place(relx=relx, rely=rely)
用法:
class App(tk.Tk):
def __init__(self):
super().__init__()
self.one = MyButton(self, 0.6, 0.9, text="1", command=self.one)
self.two = MyButton(self, 0.7, 0.9, text="2", command=self.two)
self.three = MyButton(self, 0.8, 0.9, text="3", command=self.three)
# Alternative
relx = 0.6
for cfg in [("1", self.one), ("2", self.two), ("3", self.three)]:
MyButton(self, relx, 0.9, text=cfg[0], command=cfg[1])
relx += 0.1
if __name__ == "__main__":
App().mainloop()
用 Python 測試:3.5
添加回答
舉報