Python 3 / Tkinter:更改预定义标签的字体类型,大小和颜色

时间:2018-03-23 22:57:09

标签: python tkinter fonts label frame

我正在使用Tkinter和Python 3.6(Windows 10)。我在画布上有一个框架,框架包含一个标签。在GUI的使用期间,用户从下拉菜单中选择标签属性(即,字体类型,颜色,大小)。框架及其标签的启动是:

    self.defaultLeftStringValue                     = StringVar()       
    self.defaultRightStringValue                    = StringVar()
    self.leftFrame                                  = tf.TextInFrame(self.main_container, bg = 'white', 
                                                                     height = 128, width = 128)
    self.leftFrame.place( x = 10, y = 10)
    self.leftFrame.pack_propagate(False)
    self.leftLabel                                  = Label(self.leftFrame, textvariable=self.defaultLeftStringValue).pack()

稍后,用户已使用其他方法选择字体类型,大小和颜色(doEnter :)

def doEnter(self):

    thisFontSize                                    = self.tkvarFontSize.get()
    thisFontColor                                   = self.tkvarFontFgColor.get()
    thisFontType                                    = self.tkvarFontType.get()
    self.leftFrame.config(bg=self.tkvarFontBgColor.get())
    self.rightFrame.config(bg=self.tkvarFontBgColor.get())
    font                                            = Font( family = thisFontType, size = thisFontSize )
    splitText                                       = self.text_entry.get()

    self.splitTextLeft                              = " "
    self.splitTextRight                             = " "
    if ";" in splitText:
        splitText                                   = splitText.split(";")
        self.splitTextLeft                          = splitText[0]
        self.splitTextRight                         = splitText[1]
        splitTextLeftLength                         = font.measure(self.splitTextLeft)
        splitTextRightLength                        = font.measure(self.splitTextRight)
        splitTextHeight                             = font.metrics("linespace")
        self.defaultLeftStringValue.set(self.splitTextLeft)
        self.defaultRightStringValue.set(self.splitTextRight)

这一切都很有效;输入的文本显示在左右框架的标签中。我甚至可以改变框架的背景颜色。但是,我无法弄清楚如何使用thisFontSize(value = 10,type = class int)和thisFontColor(黑色,类str)和thisFontType(agencyfb,类str)更改标签属性。希望有人能告诉我如何更改插入self.splitTextLeft等文本的属性。

1 个答案:

答案 0 :(得分:2)

此行将None分配给self.leftLabel

self.leftLabel = Label(self.leftFrame, textvariable=self.defaultLeftStringValue).pack()

您无法链接几何管理方法并保留对窗口小部件的引用。分开执行这些步骤。在您的情况下,您没有引用标签实例,因此以后无法设置其属性。

举例说明:

x = tk.Label(root, text="ok").pack()
type(x)
<class 'NoneType'>
x = tk.Label(root, text="ok")
type(x)
<class 'tkinter.Label'>