在窗口中居中许多小部件 [tkinter]

我需要将两个按钮居中,我可能需要将更多按钮居中,但我不能居中超过一个按钮,所以我需要帮助......


这是代码:


from tkinter import *

from tkinter.ttk import * 

import os


root = Tk()

root.geometry("325x100")

    

def click():

    pass

        

def click2():

    pass

            

button = Button(root, text="Button 1", command=click, width=25)

button.grid(row=0, column=0)


button2 = Button(root, text="Button 2", command=click2, width=25)

button2.grid(row=1, column=0)

      

root.grid_rowconfigure(0, weight=1)

root.grid_columnconfigure(0, weight=1)

      

root.mainloop()


千万里不及你
浏览 150回答 2
2回答

莫回无

我做了一些测试,这就是我想出的。我使用了 .pack() 方法而不是 .grid() 方法,我还使用了一个框架。我是 Python 的新手,但在这里 :)from tkinter import *from tkinter.ttk import *import osroot = Tk()root.geometry("325x100")def click():    passdef click2():    passframe = Frame(root)frame.pack(padx = 20, pady = 12)button = Button(root, text="Button 1", command=click, width=25)button.pack()button2 = Button(root, text="Button 2", command=click2, width=25)button2.pack()root.mainloop()这是它的样子:

智慧大石

不要在第一行增加重量。它迫使它扩张。不过,您可能还想考虑其他事情。您最终可能会在该行上放置其他东西,并且您可能需要那个东西来扩展该行。在当前状态下,这将导致您遇到“第 22 条军规”。您可能需要考虑创建一个框架来容纳所有按钮,并将整个框架放在根部。立即修复:from tkinter import *from tkinter.ttk import * import osroot = Tk()root.geometry("325x100")    def click():    pass        def click2():    pass            button = Button(root, text="Button 1", command=click, width=25)button.grid(row=0, column=0)button2 = Button(root, text="Button 2", command=click2, width=25)button2.grid(row=1, column=0)#this is forcing the top row to expand     #root.grid_rowconfigure(0, weight=1)   root.grid_columnconfigure(0, weight=1)      root.mainloop() 可能是更好的方法:from tkinter import *from tkinter.ttk import * import osroot = Tk()root.geometry("325x100")    def click():    pass        def click2():    pass    #by not defining row and column in grid() #~ row will be the next available one and column will be 0    button_frame = Frame(root)button_frame.grid(sticky='nswe')button_frame.grid_columnconfigure(0, weight=1)#you only need to store a reference if you intend to change/reference/destroy/forget these#if they are going to always be a button, as initially defined, a reference is dead weight          Button(button_frame, text="Button 1", command=click, width=25).grid()Button(button_frame, text="Button 2", command=click2, width=25).grid()#now you can use grid_rowconfigure without it destroying your button layout      root.grid_rowconfigure(0, weight=1)root.grid_columnconfigure(0, weight=1)      root.mainloop() 
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python