我想在框架的左側(不是中間)堆疊兩個按鈕。
我的代碼:
import tkinter as tk
from tkinter import Frame, Button, LEFT
def pressed():
print("Button Pressed!")
root = tk.Tk()
frame = Frame(root)
frame.pack()
button1 = Button(frame, text="Button1", command=pressed)
button1.pack(side=LEFT, pady=20)
button2 = Button(frame, text="Button2", command=pressed)
button2.pack(side=LEFT, ipadx=20)
root.mainloop()
我也試過:
button1.pack(side=LEFT, fill='x' pady=20)
但它不會改變輸出中的任何內容。
所需輸出:
------------------------------
| |(20px) |
|[Button1] <------------------ |
| |(20px) |
|[-(20px)-Button2-(20px)-] <-- |
| |
| |
------------------------------
代碼中的其他一切都很好,我只希望兩個按鈕都堆疊在框架的左側。
我也嘗試過這個解決方案,但它在中間放置了按鈕。
注意:我不能使用gridorplace。
uj5u.com熱心網友回復:
您的框架僅打包,沒有任何引數expand或fill引數,因此您的按鈕將保持在頂部中心,因為框架只會擴展至足以容納按鈕而不再有更多。所以為了讓按鈕出現在左邊,你需要這樣的東西。
import tkinter as tk
from tkinter import Frame, Button, LEFT
def pressed():
print("Button Pressed!")
root = tk.Tk()
frame = Frame(root)
frame.pack(expand=True, fill=tk.BOTH) #control the frame behavior
button1 = Button(frame, text="Button1", command=pressed)
button1.pack(side=tk.TOP, anchor=tk.W, pady=20)# pack top and left
button2 = Button(frame, text="Button2", command=pressed)
button2.pack(side=tk.TOP, anchor=tk.W)
root.mainloop()
或者一種不太理想的方式,設定幀大小并防止它像這樣傳播。
import tkinter as tk
from tkinter import Frame, Button, LEFT
def pressed():
print("Button Pressed!")
root = tk.Tk()
frame = Frame(root, height=1000, width=1000)
frame.pack()
frame.pack_propagate(0) #stops the frame from shrinking to fit widgets
button1 = Button(frame, text="Button1", command=pressed)
button1.pack(side=tk.TOP, anchor=tk.W, pady=20)
button2 = Button(frame, text="Button2", command=pressed)
button2.pack(side=tk.TOP, anchor=tk.W)
root.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/474312.html
