如何将Tkinter窗口设置为固定大小?
如何固定Tkinter窗口大小
要让你的Tkinter窗口保持固定大小,只需调用窗口对象的resizable()方法,传入两个False参数,分别禁止水平和垂直方向的调整。以下是具体修改方案:
核心修改点
你可以选择两种位置添加固定代码,推荐放在类初始化中更规范:
方案一:在SeaofBTCapp类的初始化方法中添加
找到SeaofBTCapp的__init__方法,在父类初始化完成后添加一行代码:
self.resizable(False, False)
方案二:在实例化窗口后添加
在app = SeaofBTCapp()之后添加:
app.resizable(False, False)
如果需要先指定窗口尺寸再固定,可搭配geometry()方法:
self.geometry("400x300") # 设置窗口为400宽、300高 self.resizable(False, False)
完整修改后的代码
import tkinter as tk LARGE_FONT= ("Verdana", 12) class SeaofBTCapp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) # 添加固定窗口大小的代码 self.resizable(False, False) container = tk.Frame(self) container.pack(side="top", fill="both", expand = False) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (StartPage, PageOne, PageTwo): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(StartPage) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self,parent) label = tk.Label(self, text="NC's Ice-Cream Shop", font=LARGE_FONT) label.pack(pady=10,padx=10) button = tk.Button(self, text=">>", command=lambda: controller.show_frame(PageOne)) button.pack() #button2 = tk.Button(self, text="Visit Page 2", # command=lambda: controller.show_frame(PageTwo)) #button2.pack() class PageOne(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="Order Details", font=LARGE_FONT) label.pack(pady=10,padx=10) button1 = tk.Button(self, text="<<", command=lambda: controller.show_frame(StartPage)) button1.pack() button2 = tk.Button(self, text=">>", command=lambda: controller.show_frame(PageTwo)) button2.pack() class PageTwo(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="Receipt", font=LARGE_FONT) label.pack(pady=10,padx=10) button1 = tk.Button(self, text="<<", command=lambda: controller.show_frame(PageOne)) button1.pack() button2 = tk.Button(self, text="New", command=lambda: controller.show_frame(StartPage)) button2.pack() app = SeaofBTCapp() app.mainloop()
内容的提问来源于stack exchange,提问作者Nitya
相关产品推荐
相关产品推荐

