简体   繁体   English

Kivy-更改按钮颜色

[英]Kivy - changing button color on press

I've recently started using kivy to design GUI for my python app. 我最近开始使用kivy为我的python应用程序设计GUI。 In the app one of the actions is sending requests to server using provided API. 在应用程序中,操作之一是使用提供的API将请求发送到服务器。 After a couple of tests I've noticed one annoying thing that happens only when I want to make a request - the button doesn't change color on press (I'm talking about default action). 经过几次测试,我发现只有在我要发出请求时才会发生一件令人讨厌的事情-按钮在按下时不会改变颜色(我说的是默认操作)。 However, it is changing when simple print() is used. 但是,当使用简单的print()时,它正在改变。

How I can fix it? 我该如何解决? Any idea? 任何想法?

This is the code of my test app: 这是我的测试应用程序的代码:

class TestApp(App):
    def build(self):
        parent = Widget()
        btn = Button(text='Add')
        btn.bind(on_press=self.add)
        parent.add_widget(btn)
        return parent

    def add(self, obj):
        print("Adding")
        request = Request(url, urlencode(post_fields).encode())
        urlopen(request)

That happened most likely because the UI froze. 发生这种情况的原因很可能是UI冻结。 The self.add is called, but right after that the UI waits until the request is done, which for you might result in that. 调用了self.add ,但是self.add UI等待直到请求完成,这可能会导致该情况。

Try to do it like this: 尝试这样做:

import threading

class TestApp(App):
    def build(self):
        parent = Widget()
        btn = Button(text='Add')
        btn.bind(on_press=self.add)
        parent.add_widget(btn)
        return parent

    def add(self, obj):
        print("Adding")
        #self.printer()  # freezing
        threading.Thread(target=self.printer).start()

    def printer(self, *args):
        while True:
            print 'blob'
TestApp().run()

Also, instead of on_press use rather on_release . 另外,代替on_press ,而是使用on_release Prevents accidental events if I remember correctly (checks for collision touch↔button area). 如果我没记错的话,可以防止意外事件(检查碰撞触摸按钮区域)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM