2017-02-18 2 views
0

私はPython 2.11を使用してTkinterにGUIを作成しています。これはOOPアプローチを使用して継承を学習しようとしています。私はtk.Buttonから継承されたButtonFieldという子クラスを作成しました。 ButtonFieldの内部私は、押されたときにボタンの色とテキストを変更するpressMeというメソッドを持っています。ボタンウィジェットを使用したTkinterでの継承の適切な使用

最終的な目標は、より清潔で管理しやすいコードのために、ButtonFieldクラスに含まれるGUIおよび関連するすべてのメソッドに多くのボタンを追加することです。

ボタンを押すと、「Press Me Method」のテキストが表示されるので、メソッドはおそらく機能していますが、ボタンウィジェットはテキストや背景色を変更しません。

import Tkinter as tk 

class MainWindow(tk.Frame): 
    def __init__(self, parent, *args, **kwargs): 
     tk.Frame.__init__(self, parent, *args, **kwargs) 
     self.parent = parent 

     self.olFrame = tk.LabelFrame(text = 'Initial Frame', bg = 'grey') 
     self.olFrame.grid(column = 0, row = 0, sticky = 'w') 

     self.simpleButton = ButtonField(self.olFrame, text = "Press Me",bg= "green" 
            ,command = ButtonField(self).pressMe) 
     self.simpleButton.grid(column = 0, row = 0) 

class ButtonField(tk.Button): 
    def __init__(self, parent, *args, **kwargs): 
     tk.Button.__init__(self, parent, *args, **kwargs) 
     self.parent = parent 

    def pressMe(self): 
     print "In Press Me Method" 
     self.configure(text = "Pressed Now", background = "yellow") 
     #self.parent.configure(self, text = "Pressed Now", background = "yellow") #returns TclError: unknow option "-text" 

root = tk.Tk() 
root.geometry('500x400') 
root.title('Test GUI') 
root.configure(background = "black") 

a = MainWindow(root) 
root.mainloop() 
+0

あなたは特定のバグに対して良い答えを持っていますが、すべてを継承する計画は良いものではありませんあなたのコードは既にそれよりも複雑になります。まったく新しいウィジェットを作っていない限り、ほとんどのtkinterの例で見られるように、作曲と委譲を使用するだけです。 – pvg

答えて

0

のコード行考えてみましょう:あなたはこれをしなかったかのようにそれはまったく同じである

self.simpleButton = ButtonField(..., command = ButtonField(self).pressMe) 

を:

another_button = Button(self) 
self.simpleButton = ButtonField(..., command=another_button.pressMe) 

あなたがある別のボタンの機能を呼び出しているのであなたが変更を見ることはありません。ボタンが自分の関数を呼び出すようにするには、次の2つのステップでそれを行う必要があります。

関連する問題