【问题标题】:tkinter Label does not respect justify option?tkinter 标签不尊重 justify 选项?
【发布时间】:2014-11-12 20:37:25
【问题描述】:

代码如下:

from tkinter import *

class PopupTk(Frame):
    def __init__(self, master=None, title="Notification", msg="New information", duration=2):
        Frame.__init__(self, master)
        self.duration = duration
        close_button = Button(self, text="C", command=self.master.destroy)
        close_button.pack(side=LEFT)
        title_label = Label(self, text=title)
        title_label.config(justify=LEFT)
        title_label.pack()
        msg_label = Label(self, text=msg)
        msg_label.config(justify=LEFT)
        msg_label.pack()
        self.pack(side=TOP, fill=BOTH, expand=YES, padx=10, pady=10)

        # get screen width and height
        ws = self.master.winfo_screenwidth()
        hs = self.master.winfo_screenheight()
        w = 300
        h = 100
        # calculate position x, y
        x = ws - w
        y = hs - h
        self.master.geometry('%dx%d+%d+%d' % (w, h, x, y))
        self.master.overrideredirect(True)
        self.master.lift()

    def auto_close(self):
        msec_until_close = self.duration * 1000
        self.master.after(msec_until_close, self.master.destroy)


if __name__ == '__main__':
    root = Tk()

    sp = PopupTk(root, duration=3)
    sp.auto_close()
    root.call('wm', 'attributes', '.', '-topmost', True)
    root.mainloop()

结果如下:

它仍然居中对齐(默认)。

我使用的是 python 3.4,并且已经在 osx 和 ubuntu 14.04 上进行了测试,顺便说一句。

【问题讨论】:

    标签: python tkinter tk


    【解决方案1】:

    您遇到的第一个问题是justify 仅影响具有多行文本的标签。您要使用的选项而不是 justifyanchor。然而,这不是你唯一的问题。

    这是开始调试此类问题的一种简单方法:在小部件周围添加临时边框。这让您可以看到边界在哪里,从而可以可视化是居中的文本还是居中的小部件(或两者兼而有之)

    title_label.config(borderwidth=1, relief="solid")
    ...
    msg_label.config(borderwidth=1, relief="solid")
    

    这样做,很明显问题不在于小部件中的文本没有左对齐,而在于小部件在其框架部分居中。

    一个快速的解决方法可能是在打包小部件时使用anchor 属性。这将强制小部件位于它被分配的包裹的左侧。

    title_label.pack(side="top", anchor="w")
    msg_label.pack(side="top", anchor="w")
    

    【讨论】:

      猜你喜欢
      • 2020-09-25
      • 2018-12-24
      • 2018-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-08
      • 1970-01-01
      相关资源
      最近更新 更多