为何CustomTkinter中winfo_width/height返回错误窗口尺寸?
问题原因及解决方案
原因
CustomTkinter的CTk窗口默认带有最小尺寸限制,默认最小宽高为500×500。当你通过geometry()设置的窗口尺寸小于这个默认最小值时,窗口会自动调整到最小尺寸,这就是指定400×400却得到500×500的原因。
解决方案
在窗口初始化时手动设置最小尺寸,覆盖默认限制即可。修改Window类的__init__方法,添加self.minsize(width, height):
import customtkinter as ctk class Window(ctk.CTk): """ App window """ def __init__(self, background_color: str, title: str, width: int, height: int): super().__init__(fg_color=background_color) self.title(title) # 设置最小尺寸,覆盖默认限制 self.minsize(width, height) self.geometry(f'{width}x{height}') @property def width(self) -> int: self.update() return self.winfo_width() @property def height(self) -> int: self.update() return self.winfo_height() def show_window(self): """ displays window :return: """ self.mainloop() if __name__ == "__main__": window = Window( background_color="gray", title="test", width=400, height=400) print("width", window.width) print("height", window.height) window.show_window()
修改后运行代码,窗口会保持400×400的尺寸,输出也会对应显示width 400和height 400。
内容的提问来源于stack exchange,提问作者AkubuoF
相关产品推荐
相关产品推荐

