gpt4 book ai didi

python - 使用 Kivy 如何在 ScrollView 中生成缩放按钮

转载 作者:太空宇宙 更新时间:2023-11-03 16:58:48 28 4
gpt4 key购买 nike

我对 kivy 还很陌生,在调整小部件的大小和定位方面遇到了一些麻烦,我正在尝试生成位于 ScrollView 内的网格布局中的按钮。当我按下右下角的按钮时,我想生成一些缩放到该按钮宽度的按钮。

Before the button is pressed

但这就是按钮的样子

After button is pressed

class RootWidget(BoxLayout):
pass

class CustomLayout(FloatLayout):

def __init__(self, **kwargs):
# make sure we aren't overriding any important functionality
super(CustomLayout, self).__init__(**kwargs)

with self.canvas.before:
Color(0, 1, 0, 1) # green; colors range from 0-1 instead of 0-255
self.rect = Rectangle(size=self.size, pos=self.pos)

self.bind(size=self._update_rect, pos=self._update_rect)

def _update_rect(self, instance, value):
self.rect.pos = instance.pos
self.rect.size = instance.size

class MainApp(App):

def build(self):
root = RootWidget()
c = CustomLayout()
root.add_widget(c)

def on_enter(self):
func = Function()
buttons = func.buttons()
root.add_widget(buttons)

get_buttons = Button(
text='Get links',
size_hint=(.5, .10),
pos=(20, 20))
root.add_widget(get_buttons)

get_buttons.bind(on_press=on_enter)
return root

class Function:
def buttons(self):
layout = GridLayout(cols=1, padding=1, spacing=10,
size_hint=(None, None), width=20)

layout.bind(minimum_height=layout.setter('height'))
for buttn in range(20):
btn = Button(text='test', size=(20, 50),
size_hint=(None, None))
layout.add_widget(btn)
# create a scroll view, with a size < size of the grid
root = ScrollView(size_hint=(None, None), size=(20, 500),
pos_hint={'center_x': .5, 'center_y': .5}, do_scroll_x=False)

root.add_widget(layout)
return root

if __name__=='__main__':
MainApp().run()

最佳答案

我强烈建议您使用 kv 文件来描述 GUI,因为它更容易阅读,因此也更容易维护。看这个例子:

测试.kv:

#:kivy 1.9.0
GridLayout:
rows: 1

LeftArea:
RightArea:


<LeftArea@FloatLayout>:

canvas:
Color:
rgb: 0, 1, 0
Rectangle:
size: self.size
pos: self.pos


<RightArea@GridLayout>:
cols: 1
size_hint_x: 0.3
spacing: '10dp'

ScrollView:
LinksGrid:
id: links_grid

GetLinksButton:
links_grid: links_grid


<LinksGrid@GridLayout>:
cols: 1
spacing: '5dp'
size_hint_y: None
height: self.minimum_height


<GetLinksButton>:
size_hint_y: 0.2
text: 'get links'
on_press: self.get_links()


<LinkButton>:
size_hint_y: None
height: '80dp'

main.py:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.uix.button import Button


class GetLinksButton(Button):

link_number = 1

def get_links(self):
for i in xrange(3):
link_button = LinkButton(
text='link number ' + str(self.link_number)
)
self.link_number += 1
self.links_grid.add_widget(link_button)


class LinkButton(Button):
pass


class Test(App):
pass


Test().run()

结果:

enter image description here

关于python - 使用 Kivy 如何在 ScrollView 中生成缩放按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35184188/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com