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')
应该使用全局方法吗? 如果可能的话,我会在课堂内对标签进行定义并在课堂外更改它的文字。
答案 0 :(得分:2)
您不需要全局变量。您有一个对实例的引用,它允许您访问所有实例变量:
ex.Label_My["text"] = "HisObject"
答案 1 :(得分:1)
如果您的问题是"我可以使用全局来设置来自课外的变量值吗?好的。 每当您想要更改全局变量的值时,您需要编写全局变量。
def changetext():
global label_text
label_text = "new text"