Montague27
Montague27

Reputation: 81

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')

it should use global method? I would defind labels inside the class and change it's text outside class if possible.

Upvotes: 0

Views: 1159

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 386352

You don't need global variables. You have a reference to the instance, which allows you to access all instance variables:

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

Upvotes: 2

Paolo Maglica
Paolo Maglica

Reputation: 36

If your question is "can I use global to set variable values from outside the class" then yes. Whenever you want to change the value of a global variable you need to write global.

def changetext():
   global label_text
   label_text = "new text"

Upvotes: 1

Related Questions