Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

python - 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...