【问题标题】:How do I comunicate with my computer through Kivy? [closed]如何通过 Kivy 与我的计算机通信? [关闭]
【发布时间】:2016-04-25 14:47:21
【问题描述】:

我想知道是否可以创建一个可以与我的计算机通信的 Kivy 应用程序。我希望能够单击我的 Kivy 应用程序(安装在我的智能手机中)中的一个按钮并触发另一个 python 脚本的执行。例如,我会单击智能手机中的一个按钮,然后我的 Windows PC 中的 Python 代码会打印“hello world”。

谢谢各位。我真的很感谢你的帮助。欢迎任何想法。

【问题讨论】:

  • 您必须在 PC 上创建可以从智能手机接收信息的服务器。它可以是 HTTP/WWW 服务器或其他。你可以使用 Flask 框架来创建它。

标签: python windows kivy


【解决方案1】:

首先,您需要一个服务器,例如 Flask。使用pip install flask 安装烧瓶。

然后,编写一个简单的服务器。该代码会将客户端发送的消息写入messages.log 文件。当然,您也可以执行其他操作,例如关闭您的 PC。

server.py 文件:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Flask
from flask import request
import time
app = Flask(__name__)


@app.route('/', methods=['POST'])
def hello_world():
    try:
        message = request.form['message']
        return do_something(message)
    except Exception, e:
        print e
        return 'error'


def do_something(message):
    with open('messages.log', 'a') as f:
        current_time = time.ctime()
        f.write(current_time + ': ' + message + '\n')
    return 'message saved'

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

运行文件。服务器的地址是http://localhost:5000

一旦你有一个工作的服务器,编写一个客户端应用程序。该代码将向服务器发送一条短信。

test.kv 文件:

#:kivy 1.9.0

MainLayout:
    cols: 1
    spacing: '30dp'
    padding: '50dp', '50dp', '50dp', '50dp'

    Label:
        id: status_label
        size_hint_y: 0.3

    TextInput:
        id: message_input

    Button:
        text: 'send message to server'
        on_press: root.send_message(message_input.text)

    Button:
        text: 'quit app'
        on_press: app.stop()

client.py 文件:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.network.urlrequest import UrlRequest
from kivy.uix.gridlayout import GridLayout
import urllib


class MainLayout(GridLayout):

    count = 1

    def send_message(self, message):
        POST_data = self._prepare_data(message)
        self._send_message(POST_data)

    def _prepare_data(self, message):
        auth_data = {'message': message}
        auth_data = urllib.urlencode(auth_data)
        headers = {
            'Content-type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }
        return {'auth_data': auth_data, 'headers': headers}

    def _send_message(self, POST_data):
        UrlRequest(
            url='http://localhost:5000/',
            req_body=POST_data['auth_data'],
            req_headers=POST_data['headers'],
            on_failure=self._on_connection_failure,
            on_error=self._on_connection_error,
            on_success=self._on_connection_success,
        )

    def _on_connection_success(self, request, result):
        self.ids.status_label.text =\
            'message %s delivered' % self.count
        self.count += 1

    def _on_connection_failure(self, request, result):
        self.ids.status_label.text = 'connection fail'

    def _on_connection_error(self, request, result):
        self.ids.status_label.text = 'connection error'


class Test(App):
    pass


Test().run()

要使用智能手机连接到服务器,然后在 UrlRequest 中作为 URL 输入计算机的 IP 地址而不是“localhost”,例如:http://192.168.0.1:5000/

【讨论】:

  • @AlejandroDapenaSanz 请将我的帖子标记为问题的答案。
  • 谢谢,但是,我必须按什么顺序运行代码,另外,kivy 代码说语法错误...:/
  • @AlejandroDapenaSanz 运行 server.py 和 client.py; test.kv 被 client.py 使用。
猜你喜欢
  • 1970-01-01
  • 2016-02-11
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 2021-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多