我知道这看起来像很多代码但是把它扔进python并运行它。你会立即看到问题,你会发现代码主要只是一个样式表。
我有一个黑框。其中一个名为“选择”的灰色框架占据了60%的高度和宽度。我想把一堆按钮放在灰框内。这些是从我创建的customButton类继承的自定义按钮。
然而,relx和依赖功能不正常。
from tkinter import *
root = Tk()
root.resizable(width=FALSE, height=FALSE)
root.geometry("1024x768")
root.config(background="black")
# The base class
class customButton(Label):
def __init__(self, *args, **kwargs):
Label.__init__(self, *args, **kwargs)
self.config(
background="black", #background of just the button
foreground="white" #font color
)
#The child class
class travelButton(customButton):
def __init__(self, *args, **kwargs): #All of this garbage is required just to
super().__init__() #change the text
self.config(text="Travel") #dynamically
def loadSelections():
selectionWindow = Label(root)
# Selection Window
selectionWindow.config(
background="gray",
foreground="white"
)
selectionWindow.place(
relwidth=0.6,
relheight=0.6,
relx=0,
rely=0
)
#What I've tried but doesn't work
travel = travelButton(selectionWindow)
travel.config(
background="red",
foreground="white",
text="Travel button. The gray should be 50%, but Tkinter is being weird about inheritance."
)
travel.place(
relwidth=0.5,
relheight=0.5,
relx=0,
rely=0
)
#De-comment this and comment out the "travel" stuff above to see what is supposed to happen
"""
greenTester = Label(selectionWindow)
greenTester.config(
background="green",
foreground="white",
text="This works, but doesn't let me take advantage of inheritance."
)
greenTester.place(
relwidth=0.5,
relheight=0.5,
relx=0,
rely=0
)
"""
loadSelections()
我需要动态创建按钮,因此继承将是一个巨大的帮助。
答案 0 :(得分:1)
您忘记使用*args, **kwargs
而travelButton
未通知Label
谁是其父母。 Label
不知道父级,因此它使用root
作为父级。
你需要
class travelButton(customButton):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
或
class travelButton(customButton):
def __init__(self, *args, **kwargs):
customButton.__init__(self, *args, **kwargs)