Tkinter中Text组件side=LEFT打包失效问题求助
解决Tkinter Text组件无法靠左显示的问题
嘿,我明白你遇到的困扰了——你想把Text组件放在窗口左上角,结果它却像默认pack()一样居中显示。其实问题确实出在你用的Frame组件上,咱们一步步来搞定:
问题根源
你创建的Frame用了默认的self.frame.pack(),这种情况下Frame会:
- 在父容器(也就是你的root窗口)里居中显示
- 只占据刚好能容纳子组件(也就是你的Text)的最小空间
所以哪怕你的Text在Frame里设置了side=LEFT,整个Frame本身还是飘在窗口中间,看起来Text就跟着居中了。
解决方案1:让Frame填满整个窗口
只需要修改Frame的pack()参数,让它填满整个root窗口,这样Text的左对齐就会相对于整个窗口的左侧:
from Tkinter import * # the ui of the main window class Ui(object): # the init of the client object def __init__(self): self.root = Tk() self.mid_height = self.root.winfo_screenheight() / 2 self.mid_width = self.root.winfo_screenwidth() / 2 self.root.title("Journey-opening") self.root.geometry("600x600+{}+{}".format(self.mid_width - 300, self.mid_height - 300)) self.root.resizable(width=0, height=0) self.cyan = "#0990CB" self.root["background"] = self.cyan self.frame = Frame(self.root) # 修改这里:让Frame填满窗口并扩展 self.frame.pack(fill=BOTH, expand=True) self.chat_box = Text(self.frame, height=30, width=50) self.chat_box.pack(side=LEFT) def open(self): self.root.mainloop() wins = Ui() wins.open()
解决方案2:直接把Text放在root上(更简洁)
如果你不需要这个Frame做其他布局,完全可以跳过它,直接把Text组件放在root窗口上,这样更直接:
from Tkinter import * # the ui of the main window class Ui(object): # the init of the client object def __init__(self): self.root = Tk() self.mid_height = self.root.winfo_screenheight() / 2 self.mid_width = self.root.winfo_screenwidth() / 2 self.root.title("Journey-opening") self.root.geometry("600x600+{}+{}".format(self.mid_width - 300, self.mid_height - 300)) self.root.resizable(width=0, height=0) self.cyan = "#0990CB" self.root["background"] = self.cyan # 直接创建Text到root上,设置左上对齐 self.chat_box = Text(self.root, height=30, width=50) self.chat_box.pack(side=LEFT, anchor=NW) def open(self): self.root.mainloop() wins = Ui() wins.open()
额外说明
fill=BOTH让Frame在水平和垂直方向都填满父容器expand=True让Frame在窗口大小变化时(不过你设置了resizable为0,这里主要是让它占满固定大小的窗口)跟着扩展anchor=NW是让Text组件对齐父容器的西北方向(也就是左上角),确保它完全贴合窗口角落
内容的提问来源于stack exchange,提问作者roy_schiff
相关产品推荐
相关产品推荐

