【问题标题】:Kivy (Python) TypeError: expected string or buffer [closed]Kivy(Python)TypeError:预期的字符串或缓冲区[关闭]
【发布时间】:2016-04-04 17:48:51
【问题描述】:

我是 Kivy 的新手,我正在尝试制作一个应用程序来计算字符串中的单词并在新的弹出窗口中显示单词的数量,即使使用 str(),我也会不断收到此错误消息。类型错误:预期的字符串或缓冲区 这是代码:

from kivy.app import App
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
import re


class CountRoot(BoxLayout):
    def clk(self, text_input):

        text = Label(text="Hello, {}!".format(text_input))
        res = re.findall("(\S+)", text)
        nw = Popup(title="Our Title!", content=res,size_hint=(.7, .7))
        nw.open()


class CountApp(App):
    def build(self):
        return CountRoot()


if __name__ == "__main__":
     CountApp().run()

这里是 kivy 文件:

<CountRoot>:
orientation: "vertical"
padding: root.width * .02, root.height * .02
spacing: "10dp"


TextInput:
    id: text_input
    hint_text: "Enter Text"
    font_size: "30dp"

Button:
    text: "Press Me"
    on_release: root.clk(text_input.text)

【问题讨论】:

  • 错误信息告诉你错误在哪一行。
  • 什么是res?它是一个字符串吗?你确定吗?你检查过吗? documentation says it's a list of strings.
  • res 是 ''re.findall("(\S+)", text)'' 的结果,它是一个数字 (int)
  • 您是否应该将int 传递给content
  • 是的,res(数字)应该显示在那个弹出窗口上

标签: python kivy


【解决方案1】:

我不确定我是否理解您想要实现的目标(因为代码所说的与描述不同),但无论哪种方式,您都将 Label 小部件分配为与标签内容相对的 text 字符串本身(正如 Jaques 所说)。

还有一件事要记住:弹出 content 接受 一个小部件(我正在传递 Label 和下面的答案)

所以你可以这样做:

KV:

...
    Button:
        text: "Press Me"
        on_release: root.clk(text_input.text)

py:

class CountRoot(BoxLayout):
    def clk(self, text_input):
        res = re.findall("(\S+)", text_input)
        nw = Popup(title="Our Title!", content=Label(text='No of words: ' + str(len(res))))
        nw.open()

(直接引用 kivy 的根部件 ids 字典):

KV:

...

Button:
    text: "Press Me"
    on_release: root.clk()

py:

class CountRoot(BoxLayout):
    def clk(self):
        text = self.ids.text_input.text
        res = re.findall("(\S+)", text)
        nw = Popup(title="Our Title!", content=Label(text='No of words: ' + str(len(res))))
        nw.open()

【讨论】:

  • 第一个解决方案奏效了!!!谢谢你:)
【解决方案2】:

text = Label(text="Hello, {}!".format(text_input))

分配给的可变文本是一个标签对象而不是一个字符串。在这样的对象上无法进行正则表达式搜索。而是在字符串上使用它。

【讨论】:

  • 这就是为什么我不知道问题出在哪里
  • 所以搜索标签的内容,而不是标签本身。
  • 这并没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方留下评论。 - From Review
  • @cpburnz 这是正确答案。 OP 没有告诉我们错误在哪一行。
  • @PeterWood 这个答案读起来更像是对我的评论。它看起来是正确的,但它没有提供解决方案。
猜你喜欢
  • 2016-01-24
  • 2016-07-15
  • 1970-01-01
  • 2013-04-18
  • 2017-08-29
  • 2020-04-02
相关资源
最近更新 更多