将全屏应用从Tkinter移植到Kivy
我写了一个仪表盘应用程序,使用的是 Tkinter
,基本上是一个全屏应用,里面有几个 tk.Label
标签,显示各种信息。
现在我想用 Kivy
重新编写这个应用,但我对这种变化的思路有点困惑。
在 Tkinter
中,基本结构是这样的:
class Dashboard(object):
def __init__(self, parent):
self.root = parent.root
self.timestr = tk.Label(self.root)
self.timestr.configure(...)
(...)
然后我会用 .configure()
来设置各种东西(比如字体、文本表格等等)。
在 Kivy
中,我想通过创建几个 FloatLayout
小部件来改变设计,这些小部件相当于上面的 tk.Label
。到目前为止,我有:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window
class Time(Widget):
def __init__(self):
self.time = "xx:xx"
def update(self):
self.time = "9:53"
class Dashboard(Widget):
Time()
class DashApp(App):
def build(self):
dash = Dashboard()
return dash
Window.fullscreen = True
DashApp().run()
还有相关的 kv
文件:
#:kivy 1.8.0
<Time>:
size: root.width, root.height / 4
pos: 0, 0
Label:
center_x: self.width / 2
top: self.top - 5
font_size: 70
text: "aaa"
当我启动应用时,它会全屏显示,但里面是空的。
我应该怎么表达我想要创建一个 Dashboad()
,然后在里面放一些小部件(比如 Time()
)呢?
2 个回答
0
与其让标签的 center_x
设为 self.width/2
(我觉得这是指标签本身),不如试试用 root.width/2
,我认为这指的是根部件,在这个例子中就是 Time
。
我很确定,在 kv 文件中,root
通常指的是这对 <>
之间的部件(也就是你正在调整的部件的根父级),self
指的是当前的部件,而 app
指的是应用程序的实例。
2
class Dashboard(Widget):
Time()
我觉得你对这个功能有些误解——其实它什么也不做。虽然创建了一个Time
对象,但并没有把它添加到Dashboard
上或者其他地方。这就是为什么你的应用程序是空白的,因为它只是一个空的Dashboard
小部件。
你需要把Time
小部件添加到仪表板上,比如在__init__
class Dashboard(Widget):
def __init__(self, **kwargs):
super(Dashboard, self).__init__(**kwargs)
self.add_widget(Time())
因为你总是想这样做,所以用kv规则来实现会更简单、更好:
<DashBoard>:
Time:
现在你可能会发现位置有些乱,但看起来你还在尝试调整这个。