下面腳本中的方法如何on_change_order實作?
import tkinter as tk
root = tk.Tk()
# Inserts labels 1 and 2 in sequence, using .pack() method
label1 = tk.Label(root, text="Label 1", bg="red", fg="white")
label1.pack(padx=5, pady=15, side=tk.LEFT)
label2 = tk.Label(root, text="Label 2", bg="green", fg="white")
label2.pack(padx=5, pady=20, side=tk.LEFT)
def on_change_order():
"""Swaps the .pack() order of the labels 1 and 2 appearing before the button."""
pass # How can this be done?
button = tk.Button(root, text='Change order', command=on_change_order)
button.pack()
root.mainloop()
當應用程式打開時,標簽 1首先出現,標簽 2出現在第二個。但是,當我單擊“更改訂單”按鈕時,我希望標簽切換位置。也就是說,我想讓回呼on_change_order改變一些東西,然后讓標簽 2首先出現,然后標簽 1 出現。
換句話說,您如何更改https://www.tcl.tk/man/tcl8.6/TkCmd/pack.html#M27中提到的“裝箱單”元素的順序?
uj5u.com熱心網友回復:
def on_change_order():
label1.pack_forget()
label2.pack_forget()
label2.pack(padx=5, pady=10, side=tk.LEFT)
label1.pack(padx=5, pady=10, side=tk.LEFT)
button.pack(after=label1)
我想你正在尋找這個。請注意,“更改訂單”按鈕不固定。如果你想讓它保存它在右邊的位置,你應該在 label1 之后設定它
uj5u.com熱心網友回復:
對于您的情況,您可以在之前重新包裝所需的標簽button:
def on_change_order():
"""Swaps the .pack() order of the labels 1 and 2 appearing before the button."""
if root.pack_slaves()[0] == label1:
label1.pack(before=button)
else:
label2.pack(before=button)
但是,使用grid管理器重新定位小部件更容易。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/416050.html
標籤:
