调整窗口大小时如何更改小部件之间的距离

2024-04-26 23:34:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我在tkinter中开发了一个应用程序,它根据名为“numberOfElements”的变量中的输入生成一定数量的按钮。 生成按钮时,它们排列在网格中。 为此,我使用了grid函数并传递了我想要生成按钮的坐标。 生成按钮后,在调整窗口大小时会相应调整按钮的大小。 但是,在调整窗口大小时,我希望调整按钮之间的距离,而不是按钮大小。 我怎么能做这样的事

from tkinter import *
from tkinter import ttk
import os
class Sample():
    def __init__(self, root):

        #Frame
        self.frame = Frame(root)
        self.root = root
        app_height = 200
        app_width = 600
        root.geometry(f'{app_width}x{app_height}')
        root.title("GUI")#window name
        
        #Grid configuration
        for x in range(30):
            Grid.columnconfigure(self.frame, x, weight=1)

        for y in range(40):
            Grid.rowconfigure(self.frame, y, weight=1)
        Grid.rowconfigure(root, 0, weight=1)
        #Grid.rowconfigure(root, 3, weight=1)
        Grid.rowconfigure(root, 2, weight=1)
        Grid.columnconfigure(root, 2, weight=1)
        Grid.columnconfigure(root, 0, weight=1)
        self.frame.grid(row=0, column=0, sticky=N+S+E+W)

        grid=Frame(self.frame)
        grid.grid(sticky=N+S+E+W, column=0, row=7, columnspan=4)
        Grid.rowconfigure(root, 7, weight=1)
        Grid.columnconfigure(root, 0, weight=1)


        numberOfElements = 20 # number of button to generate

        rows = int(numberOfElements)/10
        nelem = int(numberOfElements)%10
        #Create buttons
        for x in range(10): #colonne
            for y in range(int(rows)): #righe
                btn = Button(self.frame)
                print("x: " + str(x) + "y: " + str(y))
                btn.grid(column=x+1, row=y, sticky=N+S+E+W, padx=5, pady=10)  
                btn.config(height = 2, width = 5)
        if(nelem!=0):     #create the rest of buttons if number of elements not ends with 0
            for x in range(nelem): #colonne
                for y in range(int(rows)+1): #righe
                    btn = Button(self.frame)
                    print("x: " + str(x) + "y: " + str(y))
                    btn.grid(column=x+1, row=y, sticky=N+S+E+W, padx=5, pady=10)      
        #rows and columns configuration 
        for x in range(11):
            Grid.columnconfigure(self.frame, x, weight=1)

        for y in range(int(rows)+2):
            Grid.rowconfigure(self.frame, y, weight=1)



root = Tk()
my_gui = Sample(root)
root.mainloop()