user14611858
user14611858

Reputation:

textvariable not found in a def

I have this code :

from tkinter import *

def mine():
    global textVar
    textVar = StringVar()
    textVar.set('Text')


root = Tk()

root.title('Miner v1.0')
root.geometry('400x240')

miningButton = Button(root, text='Mine', command=mine)
miningButton.pack()

mainLabel = Label(root, textvariable=textVar)
mainLabel.pack()

root.mainloop()

I have made textVar a global variable but the mainLabel it don't find it, it says that it is undefined. But when the textVar is outside the def it works

Upvotes: 0

Views: 36

Answers (2)

user14611858
user14611858

Reputation:

Thanks to Nurqm, I have the answer:

from tkinter import *

root = Tk()

root.title('Miner v1.0')
root.geometry('400x240')

textVar = StringVar()
def mine():
    textVar.set('Text')

miningButton = Button(root, text='Mine', command=mine)
miningButton.pack()

mainLabel = Label(root, textvariable=textVar)
mainLabel.pack()

root.mainloop()```

Upvotes: 0

Nurqm
Nurqm

Reputation: 4743

It's because you never execute the mine function, so textVar variable has never existed. You can just create the variable outside the function.

from tkinter import *

root = Tk()

root.title('Miner v1.0')
root.geometry('400x240')

textVar = StringVar()
def mine():
    textVar.set('Text')

miningButton = Button(root, text='Mine', command=mine)
miningButton.pack()

mainLabel = Label(root, textvariable=textVar)
mainLabel.pack()

root.mainloop()

Upvotes: 1

Related Questions