如何解决在窗口[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()
解决方法
我做了一些测试,这是我想出的。我使用了.pack()方法而不是.grid()方法,并且我还使用了框架。我是Python的新手,但这里是:)
from tkinter import *
from tkinter.ttk import *
import os
root = Tk()
root.geometry("325x100")
def click():
pass
def click2():
pass
frame = 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 os
root = Tk()
root.geometry("325x100")
def click():
pass
def click2():
pass
button = Button(root,width=25)
button.grid(row=0,column=0)
button2 = Button(root,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 os
root = 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,width=25).grid()
Button(button_frame,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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。