I am trying to update the button text on a TKinter GUI (learning TKinter!) but am coming up against a small problem. I am getting a button1 is not defined. I am sure I am missing something stupid!
def toggleText():
if button1["text"] == "hi":
button1["text"] = "bye"
else:
button1["text"] = "hi"
def selection():
button1 = Button(tab1, text="hi", command=toggleText, height=5, width=10)
button1.grid(column=1, row=1, padx=10, pady=10)
root.mainloop()
selection()
HERE IS THE OUTPUT I GET:
if button1["text"] == "hi":
NameError: name 'button1' is not defined
CodePudding user response:
You have a couple of options, the easiest is to just use global
to make button1
a global name which can be accessed anywhere, just make sure that you call toggleText
after calling selection
:
def selection():
global button1
button1 = Button(...)
...
The other option is to use function arguments (which is better practice in this case):
# make `toggleText` accept an argument for button:
def toggleText(btn):
if btn['text'] == 'hi':
btn['text'] = 'bye'
...
def selection():
# use lambda to pass an argument and since it is a lambda name
# `button1` can be not yet defined since `lambda` is not called immediately
button1 = Button(..., command=lambda: toggleText(button1))
...
Also:
I strongly advise against using wildcard (*
) when importing something, You should either import what You need, e.g. from module import Class1, func_1, var_2
and so on or import the whole module: import module
then You can also use an alias: import module as md
or sth like that, the point is that don't import everything unless You actually know what You are doing; name clashes are the issue.
I strongly suggest following PEP 8 - Style Guide for Python Code. Function and variable names should be in snake_case
, class names in CapitalCase
. Have two blank lines around function and class declarations. Object method definitions have one blank line around them.