使用Tkinter動態調整視窗大小時的按鈕大小
Python擁有許多豐富的庫,用於建立和開發基於GUI的應用程式。Tkinter是用於建立基於GUI的應用程式的最常用的Python庫之一。它具有許多功能,例如新增小部件和其他建立應用程式所需的必要屬性。
按鈕是一個可以為某些特定任務或事件分配的小部件。但是,要動態調整按鈕小部件的大小或位置,我們可以使用Tkinter中的**Grid模組**配置其位置和佈局。要動態調整按鈕大小,可以使用**rowconfiguration()**和**coloumnconfiguration()**方法。
在Tkinter Grid系統中,有四個屬性可用於調整任何小部件的大小。這些屬性通常指的是方向,例如北、南、東和西。為了使按鈕能夠根據螢幕或視窗大小響應並動態調整大小,我們必須在其上使用**row**和**column**屬性。
示例
#Importing the tkinter library
from tkinter import *
win= Tk()
win.title("Dynamically Resize Buttons")
win.geometry("700x500")
#Configure Rows and column
Grid.rowconfigure(win, 0,weight=1)
Grid.columnconfigure(win,0,weight=1)
#Create buttons
b1= Button(win, text= "C++")
b2= Button(win, text= "Java")
#Create List of buttons
bl= [b1, b2]
row_no=0
#Loop through all the buttons and configure it row-wise
for button in bl:
Grid.rowconfigure(win,row_no, weight=1)
row_no+=1
#Adjust the position in grid and make them sticky
b1.grid(row=0, column=0, sticky= "nsew")
b2.grid(row=1, column=0, stick= "nsew")
win.mainloop()輸出
執行上述程式碼將生成輸出,並在行順序中水平顯示兩個按鈕,可以根據螢幕或視窗大小動態調整大小。

廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP