我一般来说对kivy和编程还很陌生,并且我的代码有问题。我将其简化了很多,以尝试解决根本问题,但它似乎仍无法正常工作。基本上,该kivy文件应该产生一个橙色正方形,然后将正方形的大小更改为COM7传感器生成的整数值。到目前为止,在启动时会生成一个正方形,并且传感器确实已成功将整数值传递给python。我尝试更改NumericProperty“ first_rect”的值,但是无论我如何重新定义first_rect,它的值都不会改变,矩形的大小也不会改变。我感觉有一些非常小而直接的缺失,但是我不确定是什么。
任何帮助将不胜感激!
.py文件
import serial
import time
from functools import partial
from kivy.uix.widget import Widget
from kivy.app import App
#kivy.require("1.10.0")
from kivy.clock import *
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition
from kivy.properties import ObjectProperty, NumericProperty
from kivy.properties import StringProperty
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.graphics import *
from kivy.core.window import Window
from kivy.uix.slider import Slider
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.config import Config
from kivy.lang import Builder
from functools import partial
import time
i = 10
class Bar(Widget):
pass
class Trial(Screen):
rect1 = ObjectProperty(None)
# Clock.schedule_interval(Trial().update, 1.0/60.0)
def update(self):
ser = serial.Serial('COM7', 9600, timeout=0)
thing = [0,0]
a = 1
while a==1:
Byte = ser.readline()
Byte = Byte.decode('utf-8')
Byte = Byte.strip()
Byte_proc = Byte.split(',')
if Byte_proc[0] != '':
try:
if Byte_proc[1] != '':
Byte_proc[0] = int(Byte_proc[0])
Byte_proc[1] = int(Byte_proc[1])
TestTrial_SmallApp().first_rect = Byte_proc[0]
print(TestTrial_SmallApp().first_rect)
dummy_var = int(Byte_proc[0])
print(dummy_var)
a = 0
return dummy_var
except:
pass
time.sleep(.02)
class TestTrial_SmallApp(App):
first_rect = NumericProperty(100)
def build(self):
#Builder.load_file('TestTrial.kv')
Trial().add_widget(Bar())
Clock.schedule_interval(lambda dt: Trial().update(), 1.0/60.0)
# Trial().rect1.bind(pos = (200,200))
Trial().update()
return Trial()
TestTrial_SmallApp().run()
.kv文件
#:import utils kivy.utils
#:import Window kivy.core.window
#:import Widget kivy.uix.widget
<Trial>:
id: "trial"
rect1: bar_left
canvas.before:
Color:
rgb: 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
#Rectangle orange bars
Bar:
id: bar_left
pos: 0.25*self.center_x, 0.02*self.height
<Bar>:
canvas:
Color:
rgb: utils.get_color_from_hex('#F68C43')
Rectangle:
pos: 300, 300
size: 300, app.first_rect
答案 0 :(得分:0)
在下面的声明中
TestTrial_SmallApp().first_rect = Byte_proc[0]
print(TestTrial_SmallApp().first_rect)
每个TestTrial_SmallApp()
都在创建TestTrial_SmallApp
类的新实例。我认为这不是您想要的。创建一个分配给引用的实例,然后使用该引用来使用该实例,例如
app = TestTrial_SmallApp()
app.first_rect = ...
print(app.first_rect)