Tkinter Python Toplevel

Asked

Viewed 321 times

0

I want to make the btnteste button modify the text in the label(root), I am unable to do

from tkinter import *

root = Tk()
root.geometry("800x600+600+200")
root.resizable(False, False)
root.title("Testando")
root["bg"]="orange"

teste = "Vamos testar"

espaco1 = Label(root, font=("arial", 20), text=teste, bg="yellow", 
fg="black")
espaco1.pack(side=TOP, fill=X)

dadosf = Frame(root, width=800, height=400, bg="pink")
dadosf.pack(side=TOP)

def codados():

    opt1 = Toplevel(root)
    opt1.geometry("400x200+800+300")
    opt1.resizable(False, False)
    opt1.title("Top")
    opt1["bg"] = "pink"

    espacof = Frame(opt1, width=200, height=100, bg="yellow")
    espacof.pack(side=TOP)

    def btnteste():
        global teste
        teste = "Outro Texto"

    global teste
    btn = Button(espacof, text=teste, bg="black", fg="white", 
    command=btnteste)
    btn.grid(row=0, column=0)

dados = Button(dadosf, text=teste, bg="purple", fg="yellow", 
command=codados)
dados.grid(row=0, column=0)

root.mainloop()
  • I changed my answer

1 answer

2


Your problem is that there are two variables with the same name teste. One created in the scope of the module, and another site created within the scope of the function.

You are assigning a value to the variable within the function, but this causes the creation of a new local scope variable, while the other module variable remains unchanged.

A relatively simple way to solve is to declare the variable as global within the function:

def codados(): 
    global teste
    # .... restante da funcao permanece normal ....

With this statement the external variable will be reallocated from within the function.


EDIT: If you really want to change the text of the button, you don’t need to change the variable teste. But it is necessary to create an object of the type StringVar() of tkinter:

#....
sv = StringVar()
sv.set("Vamos testar")

def btnteste():
    sv.set("Outro Texto")

btn = Button(espacof, textvariable=sv, bg="black", fg="white", command=btnteste)
btn.grid(row=0, column=0)
#....

Browser other questions tagged

You are not signed in. Login or sign up in order to post.