IordanouGiannis
IordanouGiannis

Reputation: 4357

How do I change dynamically the text of a button in tkinter?

I have a dropdown menu and a button.I am trying to change the text on the button according to the choice in the dropdown menu.I used trace,but gives me this error :

TypeError: change_button_text() takes no arguments (3 given)

This is an example:

from Tkinter import*
import Tkinter as tk
import os


def change_button_text():
    buttontext.set(widget1.get())

app=Tk()
app.title("Example")
app.geometry('200x200+200+200')

widget1 = StringVar()
widget1.set('Numbers')
files =["one",'two','three']
widget1DropDown = OptionMenu(app, widget1, *files)
widget1DropDown.config(bg = 'white',foreground='black',font=("Times",16,"italic"))
widget1DropDown["menu"].config(bg = 'white',font=("Times",12,"italic"))
widget1DropDown.pack()
widget1.trace("w", change_button_text)


buttontext=StringVar()
buttontext.set('Zero')
button1=Button(app,textvariable=buttontext,font=("Times", 16),width=15,borderwidth=5)
button1.pack(side=LEFT, padx=5,pady=8)


app.mainloop()

Any ideas?Thanks.

Upvotes: 3

Views: 4251

Answers (1)

jro
jro

Reputation: 9474

Change your function definition of change_button_text to accept parameters. Callback functions called from the trace function will always receive three arguments: the name of the variable, the index and the mode. None of these are really interesting, but your function needs to match this signature for the callback to work.

To fix it, change your callback function to look like this:

def change_button_text(name, index, mode):
    buttontext.set(widget1.get())

If you'd prefer it, you can also put a lambda in the trace call to keep the function definition clean (along the lines of, "why define the variables there if you don't use them"):

widget1.trace("w", lambda n, i, m: change_button_text())

Your callback can remain as is in this case.

Upvotes: 1

Related Questions