如何在Tkinter中動態調整按鈕文字大小?


假設我們在Tkinter框架中建立了一個按鈕和一個標籤。任務是允許按鈕文字動態調整其主視窗大小。我們可以使用**按鈕部件**建立按鈕。但是,還有其他幾個函式用於動態建立按鈕標籤。

在這個例子中,我們將建立兩個帶有標籤的按鈕。透過使用**Grid方法**,例如**rowconfigure()**和**columnconfigure()**,我們將動態調整主視窗或根視窗的大小。

為了使按鈕文字動態化,我們將使用**bind(, command)**方法,這將幫助我們將函式和方法繫結在一起。我們可以傳遞一個**回撥函式**,它通常指的是部件的新位置,以及一個**輔助函式**,根據視窗大小修改按鈕文字的更改。

首先,我們將根據寬度調整按鈕文字大小,然後根據高度調整。

示例

from tkinter import *

win= Tk()
win.geometry("700x300")

#Dynamically resize the window and its widget

Grid.rowconfigure(win, index=0, weight=1)
Grid.columnconfigure(win, index=0, weight=1)

#Define the function to change the size of the button text
def resize(e):
   #Get the width of the button
   w= e.width/10
   #Dynamically Resize the Button Text
   b.config(font=("Times New Roman",int(w)))
   #Resize the height
   if e.height <=300:
      b.config(font= ("Times New Roman",30))
   elif e.height<100:
      b.config(font= ("Time New Roman", 10))
#Let us Create buttons,

b=Button(win,text="Python")
b.grid(row= 0, column=0, sticky= "nsew")

win.bind('<Configure>', resize)
win.mainloop()

輸出

執行上述程式碼將建立一個文字為“Python”的按鈕,並且此按鈕可以動態調整大小。

更新於:2021年3月4日

914 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.