无法让 ObjectProperty 在 python 中与 Kivy 一起工作



我已经尝试完善一个解决方案一段时间了。我宁愿不在python中创建按钮,因为我试图使样式远离功能。每次我尝试使用对象属性时,它都会报告此错误。我已经在stackoverflow上搜索了很多解决方案,所以我希望有人能帮我。

TypeError: bind() takes exactly 2 positional arguments (0 given)

至于实际的代码,这里是python:

# Function import libraries
import sys
import json
import googlemaps
import pygatt
import time
import asyncio
from bleak import discover
from urllib.request import urlopen
from twilio.rest import Client
import asynckivy as ak
from asynckivy.process_and_thread import 
thread as ak_thread, process as ak_processt

# UI import libraries
from kivy.app import App
from  kivy.properties import ObjectProperty
from kivy.properties import StringProperty
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.label import Label
from kivy.uix.image import Image
from functools import partial
from kivy.event import EventDispatcher
class Screen1(Screen):
def __init__ (self,**kwargs):
super (Screen1, self).__init__(**kwargs)
pairbtn = ObjectProperty(None)
pairbtn.bind(on_press=self.pair_pressed)
# self.add_widget(pairbtn)
def pair_pressed(self, event):
async def run():
devices = await discover()
for d in devices:
print(d)
if (str(d).find('DSD TECH') != -1):
address = str(d)[0:17]
print("Device Discovered" + address)
exit()
loop = asyncio.get_event_loop()
loop.run_until_complete(run())


class Screen2(Screen):
pass

class esosApp(App):
def build(self):
screen_manager = ScreenManager()
screenone = Screen1(name='s1')
screentwo = Screen2(name='s2')
screen_manager.add_widget(screenone)
screen_manager.add_widget(screentwo)
return screen_manager    

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

这是kv文件(省略了screen2(:

#:kivy 1.11.1
<Screen1>:
orientation: "vertical"
pairbtn: pairbtn
canvas.before:
Color:
rgb: 0.965,0.965, 0.965
Rectangle:
pos: self.pos
size: self.size
Image:
source: 'icon.png'
size: self.texture_size
AnchorLayout:
anchor_y: 'top'
BoxLayout:
size_hint: 1,.07
canvas.before:
Color:
rgb: 0.6745 , 0.8353 , 0.8784
Rectangle:
pos: self.pos
size: self.size
Image:
source: 'Logo.PNG'
size: self.texture_size
AnchorLayout:
anchor_x: 'center'
anchor_y: 'bottom'
padding: (0, 10, 0, 10)
Button:
id: pairbtn
text: "Pair Device"
background_normal: ''
background_color: 0.6745 , 0.8353 , 0.8784, 1
size_hint: (.8, .1)

属性不应该也不能在类的方法中声明,而是在方法的同一级别声明,比如:

class Foo(Base):
prop = XProperty(default_value)
def __init__(self, **kwargs):
super().__init__(self, **kwargs)
# ...

很明显,你的代码不满足这个条件,而且你的逻辑pairbtn是None,所以你不能用on_press进行绑定,最后最简单的事情是用kv:进行连接

# ...
Button:
id: pairbtn
text: "Pair Device"
background_normal: ''
background_color: 0.6745 , 0.8353 , 0.8784, 1
size_hint: (.8, .1)
on_press: root.pair_pressed()

最新更新