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.


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
#Create a button
button= ttk.Button(win, text="My Button")
#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)


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

Updated on 21-Apr-2021 07:43:05