我正在将小部件放入 GUI 的弹出窗口中。我将复选框放在弹出窗口的顶部,我希望标签、条目和按钮位于它们下方的一行中。无论我尝试什么,标签、条目和按钮总是位于复选框旁边。我还没有找到使用 pack()
的解决方案。我尝试过 anchor=
但这也没有达到我想要的效果。
这是我的代码:
import tkinter as tk
from tkinter import *
CheckVar1 = IntVar()
CheckVar2 = IntVar()
class PopUp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
popup = tk.Toplevel(self, background='gray15')
popup.wm_title("EMAIL")
self.withdraw()
popup.tkraise(self)
self.c1 = tk.Checkbutton(popup, text="Current", variable=CheckVar1, onvalue =1, offvalue = 0, height=2, width=15)
self.c1.pack(side="left", fill="x")
self.c2 = tk.Checkbutton(popup, text="-1", variable=CheckVar2, onvalue =1, offvalue = 0, height=2, width=15)
self.c2.pack(side="left", fill="x")
label = tk.Label(popup, text="Please Enter Email Address", background='gray15', foreground='snow')
label.pack(side="left", fill="x", pady=10, padx=10)
self.entry = tk.Entry(popup, bd=5, width=35, background='gray30', foreground='snow')
self.entry.pack(side="left", fill="x")
self.button = tk.Button(popup, text="OK", command=self.on_button, background='gray15', foreground='snow')
self.button.pack(side="left", padx=10)
def on_button(self):
address = self.entry.get()
print(address)
time.sleep(10)
self.destroy()
app = PopUp()
app.mainloop
是否可以将某些内容放入 pack()
中,以便我可以将小部件彼此相邻放置,然后将另一个放在它们下面?
提前致谢
最佳答案
使用网格几何管理器将窗口分为两个框架,然后将小部件打包到框架中。
from tkinter import *
import time
class PopUp(Tk):
def __init__(self):
Tk.__init__(self)
CheckVar1 = IntVar()
CheckVar2 = IntVar()
popup = Toplevel(self, background='gray15')
popup.wm_title("EMAIL")
self.withdraw()
popup.tkraise(self)
topframe = Frame(popup)
topframe.grid(column=0, row=0)
bottomframe = Frame(popup)
bottomframe.grid(column=0, row=1)
self.c1 = Checkbutton(topframe, text="Current", variable=CheckVar1, onvalue=1, offvalue=0, height=2, width=15)
self.c1.pack(side="left", fill="x")
self.c2 = Checkbutton(topframe, text="-1", variable=CheckVar2, onvalue=1, offvalue=0, height=2, width=15)
self.c2.pack(side="left", fill="x")
label = Label(bottomframe, text="Please Enter Email Address", background='gray15', foreground='snow')
label.pack(side="left", fill="x", pady=10, padx=10)
self.entry = Entry(bottomframe, bd=5, width=35, background='gray30', foreground='snow')
self.entry.pack(side="left", fill="x")
self.button = Button(bottomframe, text="OK", command=self.on_button, background='gray15', foreground='snow')
self.button.pack(side="left", padx=10)
def on_button(self):
address = self.entry.get()
print(address)
time.sleep(10)
self.destroy()
app = PopUp()
app.mainloop()
一些注意事项:
无需导入 Tkinter 两次
Mainloop 是一个方法,所以它是 app.mainloop()
- CheckVar1 和 CheckVar2 必须在您的类中声明
- 驼峰式大小写(单词内大写,例如“CheckVar”)不是 Pythonic
关于python - Tkinter 小部件彼此相邻且位于下方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54037779/