在 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.