Reputation: 1
I am trying to create a label at the bottom of my Tkinter window that will update, based on the selected dropdowns, when the user hits the "generate" button. I've gotten to the point where I have my code working without error, but it does not output the label, it stays as Py_var0. Can someone tell me where I'm going wrong here? I know it has to be in the run function, or the way the Labelvar is being set incorrectly, but I'm relatively new to Python so I'm stuck! I've tried looking it up and my code looks to me like I have it set up like all the examples and answers I found, so I must be missing something obvious!
Thanks for any help:
from tkinter import *
kb = Tk()
def run():
global Labelvar
if var1.get() == "A":
Labelvar.set("Label updated")
resultlabel.config(text=Labelvar)
return
Labelvar = StringVar(kb)
var1 = StringVar(kb)
var1.set("A")
resultlabel = Label(kb, text=Labelvar)
menu = OptionMenu(kb, var1, "A", "B", "C")
generate = Button(kb, text="Go", command=run)
menu.grid(row=1, column=2)
generate.grid(row=4, column=2, sticky=W)
resultlabel.grid(row=5, column=1)
mainloop()
Upvotes: 0
Views: 1674
Reputation: 4537
I am trying to create a label at the bottom of my Tkinter window that will update, but it does not output the label
The problem can be fixed.
Avoid wildcard *
. Use import tkinter as tk
, then tk.
prefix.
StringVar()
to pass Label
widget.var1
and var1.set
.run()
function, comment out #if var1.get() == "A":
and
#Labelvar.set("Label updated")
and #return
run()
, add configure and use f-string format.Snippet modified small code:
import tkinter as tk
kb = tk.Tk()
def run():
resultlabel['text'] = f'You selected: {var1.get()}'
var1 = tk.StringVar()
resultlabel = tk.Label(kb)
menu = tk.OptionMenu(kb, var1, "A", "B", "C")
generate = tk.Button(kb, text="Go", command=run)
menu.grid(row=1, column=2)
generate.grid(row=4, column=2, sticky=tk.W)
resultlabel.grid(row=5, column=1)
kb.mainloop()
Screenshot:
Upvotes: 0
Reputation: 456
The problem is at resultlabel.config(text=Labelvar)
as text parameter requires a string, but if you pass something else (not sure though) such as StringVar, the label will grab what you passed and apply str()
to it. To solve this
from tkinter import *
kb = Tk()
def run():
if var1.get() == "A":
Labelvar.set("Label updated")
resultlabel.config(textvariable=Labelvar)
return
Labelvar = StringVar()
var1 = StringVar()
var1.set("A")
resultlabel = Label(kb, textvariable=Labelvar)
menu = OptionMenu(kb, var1, "A", "B", "C")
generate = Button(kb, text="Go", command=run)
menu.grid(row=1, column=2)
generate.grid(row=4, column=2, sticky=W)
resultlabel.grid(row=5, column=1)
#This two methods are simply for testing purposes. It works.
run()
kb.mainloop()
Upvotes: 1