2 回答

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
我做了一些測(cè)試,這就是我想出的。我使用了 .pack() 方法而不是 .grid() 方法,我還使用了一個(gè)框架。我是 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()
這是它的樣子:

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超3個(gè)贊
不要在第一行增加重量。它迫使它擴(kuò)張。不過,您可能還想考慮其他事情。您最終可能會(huì)在該行上放置其他東西,并且您可能需要那個(gè)東西來擴(kuò)展該行。在當(dāng)前狀態(tài)下,這將導(dǎo)致您遇到“第 22 條軍規(guī)”。您可能需要考慮創(chuàng)建一個(gè)框架來容納所有按鈕,并將整個(gè)框架放在根部。
立即修復(fù):
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)
#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, 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()
添加回答
舉報(bào)