Get the text of a button widget in Tkinter

PythonTkinterServer Side ProgrammingProgramming

Let us suppose that for a particular application, we want to retrieve the button value by its name. In such cases, we can use the .cget() function. Every tkinter widget supports the .cget() function, as it can be used to retrieve the widget configuration such as value or name.

Example

In this particular example, we will create a button and then store the button text in a variable "mytext". Using the variable, we will display the text in a Label widget.

#Import tkinter library
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame or window
win= Tk()
#Set the geometry of tkinter frame
win.geometry("750x250")
#Create a button
button= ttk.Button(win, text="My Button")
button.pack()
#Get the text of Button
mytext= button.cget('text')
#Create a label to print the button information
Label(win, text=mytext, font= ('Helvetica 20 bold')).pack(pady=20)
win.mainloop()

Output

Executing the above code will display a window with a button and a text label showing the button text.

raja
Published on 21-Apr-2021 07:40:27
Advertisements