python - Kivy标签验证IP地址时无法刷新
问题描述
我正在使用树莓派模块构建 Kivy 界面。在用户界面中,我有显示 Ip 地址的状态屏幕。如果我断开以太网电缆,屏幕假设给我错误标签(kivy screenone label:IpAddress),当我重新连接以太网电缆,标签应更新回 IP 地址。不幸的是,当我断开以太网电缆应用程序时显示“错误”,但是当我重新连接以太网时,它没有显示我的 IP 地址。IP地址标签保持为“错误”..
##this is the root widget
class Menu(BoxLayout):
manager = ObjectProperty(None)
def __init__(self, **kwargs):
super(Menu, self).__init__(**kwargs)
Window.bind(on_keyboard=self._key_handler)
#btn1 = ActionButton(text='',icon='./assest/usb.jpg')
def _key_handler(self, instance, key, *args):
if key is 27:
self.set_previous_screen()
return True
def set_previous_screen(self):
if self.manager.current != 'home':
#self.manager.transition.direction = 'left'
self.manager.transition = SwapTransition()
class ScreenOne(Screen,BoxLayout):
stringIP=subprocess.check_output(["hostname", "-I"]).split()[0]
print_ip = StringProperty(str(stringIP).strip("b'"))
def __init__(self, **kwargs):
super(ScreenEnergy, self).__init__(**kwargs)
#Clock.schedule_interval(self.update_ip, 1)
scheduler1 = BackgroundScheduler()
scheduler1.add_job(self.update_ip, 'interval', seconds=1)
scheduler1.start()
# #self.update_ip()
print("status window")
def update_ip(self,*args):
try:
# connect to the host -- tells us if the host is actually
# reachable
socket.create_connection(("www.google.com", 80))
self.print_ip
print("ip")
#print("connected")
return True
except OSError:
self.ids.ipAddress.text="[b][color=ff0000]Error[/color][/b]"
print("not Ip ")
return False
# try:
# #socket.inet_aton(self.print_ip)
# #socket.inet_pton(socket.AF_INET6, self.print_ip)
# self.print_ip='\b(([1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
# self.ids.ipLabel.text="faffxga"
# # legal
# except socket.error:
# self.ids.ipLabel.text="adadadsadsa"
# return False
# # Not legal
class MenuApp(FlatApp):
def build(self):
my_callback=Menu()
#ip_call =ScreenEnergy()
scheduler = BackgroundScheduler()
scheduler.add_job(my_callback.is_connected, 'interval', seconds=1)
#scheduler.add_job(ip_call.update_ip, 'interval', seconds=1)
scheduler.start()
return my_callback
if __name__ == '__main__':
MenuApp().run()
#:kivy 1.10.0
#:import hex kivy.utils.get_color_from_hex
#:import Factory kivy.factory.Factory
<Menu>:
canvas.before:
Rectangle:
pos: self.pos
size: self.size
manager: screen_manager
orientation: "vertical"
ActionBar:
size_hint_y: 0.15
background_image: ''
background_color: 0.349, 0.584, 0.917, 1
ActionView:
ActionPrevious:
ActionButton:
id:motorBtn
text:''
icon:'./assest/Ethernet.jpg'
Manager:
id: screen_manager
<ScreenOne>:
BoxLayout:
orientation: 'vertical'
WrappedLabel:
id:welcomeStatus
text: "[b]Status[/b]"
font_size:min(root.width,root.height)/15
GridLayout:
cols:2
row: 3
padding:root.width*.02,root.height*.03
spacing:min(root.width,root.height)*.02
Label:
id:ipLabel
size_hint_x: .15
color: 0, 0, 0, 1
text: '[b]IP Address :[/b]'
markup:True
Label:
id:ipAddress
size_hint_x: .15
color: 0, 0, 0, 1
text: root.print_ip
color: 1, 0, 0, 1
bold:True
markup:True
<Screen 2>:
<Manager>:
id: screen_manager
更新二: 在对代码进行必要的修改后,终端上不再出现错误……至少这是一个好兆头!
class ScreenOne(Screen,BoxLayout):
print_ip = StringProperty('')
def __init__(self, **kwargs):
super(ScreenEnergy, self).__init__(**kwargs)
Clock.schedule_interval(self.update_ip, 1)
print("status window")
def update_ip(self,*args):
try:
# connect to the host -- tells us if the host is actually
# reachable
socket.create_connection(("www.google.com", 80))
stringIP = subprocess.check_output(["hostname", "-I"]).split()[0]
self.print_ip = str(stringIP).strip("b'")
print("ip={self.print_ip}")
return True
except OSError:
self.ids.ipAddress.text="[b][color=ff0000]Error[/color][/b]"
print("not Ip ")
return False
看起来像代码卡在 除了 OSError:因为它没有变回以太网地址。
解决方案
问题
调用后块print_ip
内不重置属性。try
socket.create_connection()
解决方案
在class ScreenOne
处,执行以下操作:
- 通话
stringIP=subprocess.check_output(["hostname", "-I"]).split()[0]
后移至socket.create_connection()
- 将类属性替换
print_ip = StringProperty(str(stringIP).strip("b'"))
为print_ip = StringProperty('')
- 通话
self.print_ip = str(stringIP).strip("b'")
后添加stringIP = subprocess.check()
- 替换
self.ids.ipAddress.text
为self.print_ip
片段
class ScreenOne(Screen):
print_ip = StringProperty('')
...
def update_ip(self,*args):
try:
# connect to the host -- tells us if the host is actually
# reachable
socket.create_connection(("www.google.com", 80))
stringIP = subprocess.check_output(["hostname", "-I"]).split()[0]
self.print_ip = str(stringIP).strip("b'")
print(f"ip={self.print_ip}")
except OSError:
self.print_ip = "[b][color=ff0000]Error[/color][/b]"
print("not Ip ")
推荐阅读
- r - 具有离散似然和连续先验的 jags 算法是什么
- php - 从 SQL 数据库中检索数据并插入 PHP 数组
- javascript - Swiper spaceBetween 无法正常工作
- python - 使用 cv2 时框架没有响应。视频()
- sql - 有条件地加入 pandas
- swagger - 如何在 swagger 中定义具有 n 个属性的对象
- ios - 如何在 React Native 0.60.0 和 react-native-carplay 之间进行配置?
- javascript - setState 与更新程序回调的实际用法,而不是在 React JS 中传递对象
- javascript - 为每个表格行JS设置一个计时器
- c# - 两次调用 WebApi 时出现 ServerProtocolViolation 错误