【发布时间】:2014-02-16 00:36:55
【问题描述】:
如何在运行时根据文本量动态调整标签或按钮的大小,尤其是 text_size 和 height?
我知道这个问题已经以一种方式回答了这个问题:
Dynamically resizing a Label within a Scrollview?
我在部分代码中反映了该示例。
问题是在运行时动态调整标签和按钮的大小。使用,例如:
btn = Button(text_size=(self.width, self.height), text='blah blah')
...等等,只会让程序认为(并且在逻辑上如此)“self”指的是包含按钮的类。
那么,如何在python语言中动态调整这些属性的大小,而不是kivy呢?
我的示例代码:
import kivy
kivy.require('1.7.2') # replace with your current kivy version !
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
i = range(20)
long_text = 'sometimes the search result could be rather long \
sometimes the search result could be rather long \
sometimes the search result could be rather long '
class ButtonILike(Button):
def get_text(self):
return long_text
class HomeScreen(Screen):
scroll_view = ObjectProperty(None)
def __init__(self, *args, **kwargs):
super(HomeScreen, self).__init__(*args, **kwargs)
layout1 = GridLayout(cols=1, spacing=0, size_hint=(1, None), \
row_force_default=False, row_default_height=40)
layout1.bind(minimum_height=layout1.setter('height'),
minimum_width=layout1.setter('width'))
layout1.add_widget(ButtonILike())
for result in i:
btn1 = Button(font_name="data/fonts/DejaVuSans.ttf", \
size_hint=(1, None), valign='middle',)#, \
#height=self.texture_size[1], text_size=(self.width-10, None))
btn1.height = btn1.texture_size[1]
btn1.text_size = (btn1.width-20, layout1.row_default_height)
btn1.text = long_text
btn2 = Button(font_name="data/fonts/DejaVuSans.ttf", \
size_hint=(1, None), valign='middle')
btn2.bind(text_size=(btn2.width-20, None))
btn2.text = 'or short'
layout1.add_widget(btn1)
layout1.add_widget(btn2)
scrollview1 = self.scroll_view
scrollview1.clear_widgets()
scrollview1.add_widget(layout1)
class mybuttonsApp(App):
def build(self):
return HomeScreen()
if __name__ == '__main__':
mybuttonsApp().run()
还有kv文件:
#:kivy 1.7.2
<ButtonILike>:
text_size: self.width-10, None
size_hint: (1, None)
height: self.texture_size[1]
text: root.get_text()
#on_release: root.RunSearchButton_pressed()
<HomeScreen>:
scroll_view: scrollviewID
AnchorLayout:
size_hint: 1, .1
pos_hint: {'x': 0, 'y': .9}
anchor_x: 'center'
anchor_y: 'center'
Label:
text: 'Button Tester'
ScrollView:
id: scrollviewID
orientation: 'vertical'
pos_hint: {'x': 0, 'y': 0}
size_hint: 1, .9
bar_width: '8dp'
您可以看到我从 kv 文件中添加了按钮,该按钮在列表顶部显示了我想要的所有行为。在运行时调整窗口大小,您可以看到它的神奇之处。当然,更改 text_size 也可以让我对齐文本。
我根本无法在 python 端实现相同的行为。我的应用程序要求在运行时创建按钮。我认为答案可能在于“bind()”,尽管不可否认,我不确定我在尝试中是否正确使用了它,或者我是否完全理解它。您可以看到我尝试使用“btn2”,我认为它会将文本扔到左侧(因为 halign 默认为左侧),但似乎没有做任何事情。
感谢您的帮助。
【问题讨论】:
标签: python dynamic resize label kivy