在 Tkinter 中获取按钮组件的文本


假设对于某个特定的应用程序,我们需要通过其名称检索按钮值。在这种情况下,我们可以使用.cget() 函数。每个 Tkinter 组件都支持 .cget() 函数,因为该函数用于检索组件的配置,例如值或名称。

示例

在这个特定的示例中,我们将创建一个按钮,然后将按钮文本存储在一个变量“mytext”中。使用该变量,我们将在标签组件中显示文本。

#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()

输出

执行以上代码将显示一个窗口,其中包含一个按钮和一个显示按钮文本的文本标注。

更新于: 2021 年 4 月 21 日

11K+ 浏览量

开启你的职业

完成课程认证

开始
广告
© . All rights reserved.