2015-12-29 46 views
0

我知道這看起來像很多代碼,但把它扔進python並運行它。您會立即看到問題,並且您會看到代碼大多隻是樣式表。Tkinter基於繼承改變行爲

我有一個黑框。裏面是一個名爲「選擇」的灰色框架,佔據了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

也許你應該使用'tkinter.Frame'創建'selectionWindow'。 'travelButton'應該在'super().__ init __()'中使用'* args,** kwargs'。' – furas

+0

代碼中的縮進需要修復。 –

回答

1

您忘記使用*args, **kwargstravelButton未通知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) 
+0

這解決了它!謝謝! –