How would I be able to have a button that's command is to return it's text in the button to a variable

Recommended Answers

You could bind the event to pass certain arguments ...

# Tkinter, show the text of the button that has been clicked

# for Python3 use tkinter
import Tkinter as tk

def click(event):
    s = "clicked: " + event.widget.cget("text")
    root.title(s)

root = tk.Tk()
root.geometry("300x50+30+30")

b1 = tk.Button(root, …
Jump to Post

All 2 Replies

You could bind the event to pass certain arguments ...

# Tkinter, show the text of the button that has been clicked

# for Python3 use tkinter
import Tkinter as tk

def click(event):
    s = "clicked: " + event.widget.cget("text")
    root.title(s)

root = tk.Tk()
root.geometry("300x50+30+30")

b1 = tk.Button(root, text="button1")
b1.bind("<Button-1>", click)
b1.pack()

b2 = tk.Button(root, text="button2")
b2.bind("<Button-1>", click)
b2.pack()

root.mainloop()

You can also use lambda or a partial function to pass arguments ...

''' tk_button_text102.py
show the text of the Tkinter button that has been clicked
'''

# for Python3 use tkinter
import Tkinter as tk

def click(val):
    sf = "clicked: {}".format(val)
    root.title(sf)

root = tk.Tk()
root.geometry("300x80+80+50")

text1 = "button1"
cmd1 = lambda: click(text1)
b1 = tk.Button(root, text=text1, command=cmd1)
b1.pack(pady=10)

text2 = "button2"
cmd2 = lambda: click(text2)
b2 = tk.Button(root, text=text2, command=cmd2)
b2.pack()

root.mainloop()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.