謝謝閱讀:
目標:
我正在練習使用 OOP,并希望為我正在使用 tkinter 創建的標簽小部件創建一個帶有類變數的類。通過這種方式,我可以創建許多標簽,而無需為每個標簽指定相同的字體、字體大小、顏色等。
問題:
當一個類實體還需要參考 tkinter 方法時,我無法弄清楚如何呼叫它。(或者,我是否應該在創建類時嘗試包含 tkinter 參考?)
這是我所擁有的一個例子:
import tkinter as tk
class ui_Labels:
"This class sets the baseline characteristics for the widgets, including font, font size, and colors"
#If I understand correctly, below are called class attributes#
tkLabel = tk.Label
rootRef = uiRoot
varFont = "Calibri"
fontSize = 14
varFG = "f2f2f2"
varBG = "#3b3b3b"
#Constructor
def __init__(self, name, varText):
self.name = name
self.varText = varText
# CLASS OBJECTS
sectionHeader = ui_Labels("Section Header","Magic XML Iterator")
# Attempt to call the instance (not sure if that's the correct phrasing
tk.Label(sectionHeader)
何時將 sectionHeader 物件作為 tk.Label 呼叫,我收到 AttributeError 訊息:“ui_Labels' 物件沒有屬性 'tk'。
看起來訊息是說我需要在類中參考 tk 方法,但我不確定如何最好地這樣做。
TL;DR 問題:
有沒有人對為了制作 tkinter Widget 模板而撰寫類或其關聯物件的最佳方式提出建議?
謝謝!
最好的,
克里斯
uj5u.com熱心網友回復:
您不希望 aLabel成為類屬性。相反,您需要定義Labelin __init__。您還需要將 root/parent 作為引數傳入,__init__以便您可以使用它來創建標簽。您不能將它作為屬性,因為它不一定每次都相同,并且無論如何都沒有在您的代碼中定義。
基本上你想要的是一個自定義小部件,你可以像普通小部件一樣創建、網格/打包和互動,但有一些自定義引數。關于如何使用您的代碼將自定義小部件創建為類的更正確示例是:
import tkinter as tk
# Your class
class ui_Labels():
'''This class sets the baseline characteristics
for the widgets, including font, font size, and colors
'''
# Attributes
varFont = "Calibri"
fontSize = 14
varFG = "#F2F2F2"
varBG = "#3b3b3b"
# Constructor
def __init__(self, parent, name, varText):
self.parent = parent
self.name = name
self.varText = varText
self.label = tk.Label(
parent,
text = varText,
fg = self.varFG,
bg = self.varBG,
font = (self.varFont, self.fontSize)
)
# Allows you to grid as you would normally
# Can subsitute pack() here or have both class methods
def grid(self, **kwargs):
self.label.grid(kwargs)
# Main GUI
root = tk.Tk()
# Create an instance of your class
sectionHeader = ui_Labels(root, "Section Header","Magic XML Iterator")
sectionHeader.grid(row=1, column=2)
root.mainloop()
uj5u.com熱心網友回復:
我建議你閱讀一些關于 Python OOP 的教程。
以下是根據您的代碼創建自定義標簽類的示例:
import tkinter as tk
# custom label class inherited from tk.Label
class ui_Label(tk.Label):
'''
This class sets the baseline characteristics for the widget,
including font, font size and colors
'''
# class attributes
varFont = "Calibri"
fontSize = 14
varFG = "#f2f2f2"
varBG = "#3b3b3b"
# Constructor: added parent argument
def __init__(self, parent, name, varText):
kwargs = {
'text': varText,
'font': (self.varFont, self.fontSize),
'fg': self.varFG,
'bg': self.varBG,
}
# need to call constructor of inherited class
super().__init__(parent, **kwargs)
# I don't know what the purpose of 'name' is
# so just use an instance variable to save it
self.name = name
root = tk.Tk()
# create instance of custom label
sectionHeader = ui_Label(root, "Section Header", "Magic XML Iterator")
sectionHeader.pack()
root.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/365481.html
