使用 pack() 时不显示按钮
Button not being displayed when using pack()
我正在尝试创建一个 GUI 应用程序(刚刚开始),但我 运行 遇到了问题。
当我使用 .pack()(我需要使用)时,按钮没有显示,但如果我使用 .grid(),它会显示。
这是代码:
class TemperaturePlotApp(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent)
self.master.title("Max Temperature")
self.button = Button(self, text="Browse", command=self.load_file,
width=10, *args, **kwargs)
self.button.pack(side="left", fill="both", expand=True)
def load_file(self):
fname = askopenfilename(filetypes=(("Text File", "*.txt")))
if fname:
try:
print("""here it comes: self.settings["template"].set(fname)""")
except: # <- naked except is a bad idea
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
return
def main():
root = tk.Tk()
app = TemperaturePlotApp(root)
root.geometry("800x400")
root.mainloop()
if __name__ == '__main__':
main()
如果我使用 .grid(),它会起作用:
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
self.button = Button(self, text="Browse", command=self.load_file, width=10)
self.button.grid(row=1, column=0, sticky=W)
我必须使用 .pack(),而不是网格,所以如果有人能解释我做错了什么,我将不胜感激。
谢谢
科里
您的主要问题是您没有打包您的TemperaturePlotApp
小部件(派生自Frame
)。试试下面的代码:
...
app = TemperaturePlotApp(root)
app.pack()
...
另请注意,您可能正在通过以下方式导入 tkinter:
import tkinter as tk
因为您是从 Frame
小部件继承的,使用的是:
class TemperaturePlotApp(tk.Frame):
另一方面,您正在尝试使用以下方法创建按钮:
self.button = Button(...)
这意味着您正在使用另一个库中的另一个按钮(例如 ttk
)或者您遇到了冲突或类似情况。您可能希望它像:
self.button = tk.Button(...)
我正在尝试创建一个 GUI 应用程序(刚刚开始),但我 运行 遇到了问题。
当我使用 .pack()(我需要使用)时,按钮没有显示,但如果我使用 .grid(),它会显示。
这是代码:
class TemperaturePlotApp(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent)
self.master.title("Max Temperature")
self.button = Button(self, text="Browse", command=self.load_file,
width=10, *args, **kwargs)
self.button.pack(side="left", fill="both", expand=True)
def load_file(self):
fname = askopenfilename(filetypes=(("Text File", "*.txt")))
if fname:
try:
print("""here it comes: self.settings["template"].set(fname)""")
except: # <- naked except is a bad idea
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
return
def main():
root = tk.Tk()
app = TemperaturePlotApp(root)
root.geometry("800x400")
root.mainloop()
if __name__ == '__main__':
main()
如果我使用 .grid(),它会起作用:
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
self.button = Button(self, text="Browse", command=self.load_file, width=10)
self.button.grid(row=1, column=0, sticky=W)
我必须使用 .pack(),而不是网格,所以如果有人能解释我做错了什么,我将不胜感激。
谢谢 科里
您的主要问题是您没有打包您的TemperaturePlotApp
小部件(派生自Frame
)。试试下面的代码:
...
app = TemperaturePlotApp(root)
app.pack()
...
另请注意,您可能正在通过以下方式导入 tkinter:
import tkinter as tk
因为您是从 Frame
小部件继承的,使用的是:
class TemperaturePlotApp(tk.Frame):
另一方面,您正在尝试使用以下方法创建按钮:
self.button = Button(...)
这意味着您正在使用另一个库中的另一个按钮(例如 ttk
)或者您遇到了冲突或类似情况。您可能希望它像:
self.button = tk.Button(...)