在 class 之外更改 tkinter canvas 的文本
Change tkinter canvas's text outside the class
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')
应该用全局方法?
如果可能,我会在 class 内定义标签,并在 class 外更改它的文本。
如果您的问题是 "can I use global to set variable values from outside the class" 那么是的。
每当您想更改全局变量的值时,都需要编写 global.
def changetext():
global label_text
label_text = "new text"
您不需要全局变量。您有实例的引用,它允许您访问所有实例变量:
ex.Label_My["text"] = "HisObject"
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')
应该用全局方法? 如果可能,我会在 class 内定义标签,并在 class 外更改它的文本。
如果您的问题是 "can I use global to set variable values from outside the class" 那么是的。 每当您想更改全局变量的值时,都需要编写 global.
def changetext():
global label_text
label_text = "new text"
您不需要全局变量。您有实例的引用,它允许您访问所有实例变量:
ex.Label_My["text"] = "HisObject"