Marcelo Cid Valerio
Marcelo Cid Valerio

Reputation: 1

Python Script -Tkinter problem - TK doesnt work inside a function

I have a problem here with tkinter. I need to use it within a DEF to call it at various points in my script. But when I do that, the Command function no longer recognizes the TK elements. To explain better, I made 2 codes. The first one works perfect. The second, the TK is inside a function. That second one doesn't work.

Script ok, bellow

from tkinter import *

fenster = Tk()
fenster.title("Window")

def switch():
    b1["state"] = DISABLED

#--Buttons
b1=Button(fenster, text="Button")
b1.config(height = 5, width = 7)
b1.grid(row=0, column=0)

b2 = Button(text="disable", command=switch)
b2.grid(row=0,column=1)

fenster.mainloop()

And here, not ok code, inside a function. That gives de error NameError: name 'b1' is not defined

from tkinter import *

def switch():
    b1["state"] = DISABLED

def funcao():
    fenster = Tk()
    fenster.title("Window")

    #--Buttons
    b1=Button(fenster, text="Button")
    b1.config(height = 5, width = 7)
    b1.grid(row=0, column=0)

    b2 = Button(text="disable", command=switch)
    b2.grid(row=0,column=1)

    fenster.mainloop()

funcao()

Please, could you help me? Best Regards

Upvotes: 0

Views: 127

Answers (1)

pythoncraft
pythoncraft

Reputation: 140

You create the b1 variable in the funcao function, so it is created as funcao's local variable. Local variables are accessible only from the function where they are created. In the first example, you created a global variable (not in a function) so it is accessible from outside of a function but also inside of any function. There are many solutions, so here is one of them:

For example: using nested functions

from tkinter import *

def funcao():

    def switch():
        b1["state"] = DISABLED

    fenster = Tk()
    fenster.title("Window")

    #--Buttons
    b1=Button(fenster, text="Button")
    b1.config(height = 5, width = 7)
    b1.grid(row=0, column=0)

    b2 = Button(text="disable", command=switch)
    b2.grid(row=0,column=1)

    fenster.mainloop()

This works, because the switch function is inside the funcao function, so you can access the funcao's local variables.

Hope it helps.

Upvotes: 1

Related Questions