【发布时间】:2017-05-26 02:24:19
【问题描述】:
正如您从我的代码中看到的那样,我将 tk.Frame 子类化为 tkinter gui 创建自定义小部件。我将在主 gui 中实例化此类,并且需要定期更改其中标签的值。如果我使用 tkinter 变量类 StringVar() 我将需要使用它的 .set() 方法来更改引用它们的标签的值。
这是不好的做法吗?我的意思是,如果我以外的其他人要使用这个自定义小部件,他们必须知道使用 .set() 方法来传递一个新值。我觉得这件事有些不对劲……也许我想多了。谢谢。
import tkinter as tk
class CurrentTempFrame(tk.Frame):
def __init__(self, parent, width=200, height=120,
background_color='black',
font_color='white',
font = 'Roboto'):
# Call the constructor from the inherited class
tk.Frame.__init__(self, parent, width=width, height=height,
bg=background_color)
# Class variables - content
self.temperature_type = tk.StringVar()
self.temperature_type.set('Temperature')
self.temperature_value = tk.StringVar()
self.temperature_value.set('-15')
self.temperature_units = tk.StringVar()
self.temperature_units.set('°F')
self.grid_propagate(False) # disables resizing of frame
#self.columnconfigure(0, weight=1)
#self.rowconfigure(0, weight=1)
title_label = tk.Label(self,
textvariable=self.temperature_type,
font=(font, -20),
bg=background_color,
fg=font_color)
value_label = tk.Label(self,
textvariable=self.temperature_value,
font=(font, -80),
bg=background_color,
fg=font_color)
units_label = tk.Label(self,
textvariable=self.temperature_units,
font=(font, -50),
bg=background_color,
fg=font_color)
title_label.grid(row=0, column=0)
value_label.grid(row=1, column=0)
units_label.grid(row=1, column=1, sticky='N')
if __name__ == "__main__":
root = tk.Tk()
current_temp = CurrentTempFrame(root, font_color='blue')
current_temp.temperature_value.set('100')
current_temp.grid(column=0, row=0, sticky='NW')
root.mainloop()
【问题讨论】:
标签: python python-3.x user-interface tkinter