2016-08-11 22 views
0
from tkinter import * 

class MainBattle(Frame): 
    def __init__(self, parent): 
     Frame.__init__(self, parent) 
     self.parent = parent   
     self.initUI() 
    def initUI(self): 
     global canvas 
     self.parent.title('Python') 
     self.pack(fill = BOTH, expand = 1) 
     canvas = Canvas(self) 
     self.Label_My = Label(self, text = 'MyObject') 


     self.Label_My.place(x = 470, y = 35) 
     canvas.pack(fill = BOTH, expand = 1) 
     canvas.update() 
    def aa(self): 
     self.Label_My['text'] = 'HisObject' 

def Change(): 
    Label_My['text'] = 'HisObject' 

root = Tk() 
ex = MainBattle(root) 
root.geometry('700x500') 

グローバルメソッドを使用する必要がありますか? 私はクラス内のラベルを定義し、可能ならばクラス外のテキストを変更します。クラス外のtkinterキャンバスのテキストを変更する

答えて

2

グローバル変数は必要ありません。インスタンスへの参照があり、すべてのインスタンス変数にアクセスできます。

ex.Label_My["text"] = "HisObject" 
+0

グローバルメソッドを使用すると便利です。しかし、両方の助けてくれてありがとう:) – Montague27

1

「グローバル変数を使用してクラス外から変数値を設定できますか」という質問がある場合は「はい」です。 グローバル変数の値を変更したい場合は、グローバルに書き込む必要があります。

def changetext(): 
    global label_text 
    label_text = "new text" 
関連する問題