【问题标题】:Python- How to place two buttons left-right and next to each other in the middle of screen?Python-如何在屏幕中间左右放置两个按钮并彼此相邻?
【发布时间】:2025-12-15 08:20:06
【问题描述】:

首先,我阅读了相关讨论: How can I put 2 buttons next to each other?.

但是,我仍然对此感到困惑。我的代码:

#导入需要的库

from tkinter import *
from tkinter import ttk
import random


win = Tk()
win.geometry("750x250")

def clear():
   entry.delete(0,END)
def display_num():
   for i in range(1):
      entry.insert(0, random.randint(5,20))

entry= Entry(win, width= 40)
entry.pack()
button1= ttk.Button(win, text= "Print", command=display_num)
button1.pack(side= LEFT)
button2= ttk.Button(win, text= "Clear", command= clear)
button2.pack(side=LEFT)

win.mainloop()

现在我得到了

我想在屏幕中间的条目(白框)下方有两个按钮。
如何解决?谢谢!

【问题讨论】:

  • 你可以使用布局管理器

标签: python tkinter button


【解决方案1】:

你可以再做一个tk.Frame,横向排列,下面打包;例如:

entry= Entry(win, width= 40)
entry.pack()
buttons = ttk.Frame(win)
buttons.pack(pady = 5)
button1= ttk.Button(buttons, text= "Print", command=display_num)
button1.pack(side = LEFT)
button2= ttk.Button(buttons, text= "Clear", command= clear)
button2.pack()

您也可以使用grid layout manager

entry= Entry(win, width= 40)
entry.grid(row = 0, column = 0, columnspan = 2)
button1= ttk.Button(win, text= "Print", command=display_num)
button1.grid(row = 1, column = 0)
button2= ttk.Button(win, text= "Clear", command= clear)
button2.grid(row = 1, column = 1)

【讨论】:

    【解决方案2】:

    使用包意味着使用包裹,因此在我们进一步讨论时,想象一下您的小部件周围有一个矩形。默认情况下,您的值如下所示:

    widget.pack(side='top',expand=False,fill=None,anchor='center')
    

    要将小部件放在您喜欢的位置,您需要通过这些参数对其进行定义。边决定它应该添加到哪个方向。扩展告诉您的包裹消耗主控中的额外空间。 fill 告诉您的小部件在其包裹中以 xyboth 方向伸展。您还可以选择将您的小部件锚定在 eastwestnorthsouth 或组合的地块中。

    from tkinter import *
    from tkinter import ttk
    import random
    
    
    win = Tk()
    win.geometry("750x250")
    
    def clear():
       entry.delete(0,END)
    def display_num():
       for i in range(1):
          entry.insert(0, random.randint(5,20))
    
    entry= Entry(win)
    entry.pack(fill='x')
    button1= ttk.Button(win, text= "Print", command=display_num)
    button1.pack(side= LEFT,expand=1,anchor='ne')
    button2= ttk.Button(win, text= "Clear", command= clear)
    button2.pack(side=LEFT,expand=1,anchor='nw')
    
    win.mainloop()
    

    要了解有关组织小部件和 tkinter 几何管理的更多信息,see my answer here

    【讨论】:

      最近更新 更多