2016-04-04 126 views
-2

我是Kivy的新手,我試圖製作一個應用程序來計算字符串中的單詞數量,並在新的彈出框中顯示單詞數量,並且我不斷收到此錯誤消息即使使用str()。類型錯誤:預期字符串或緩衝區 下面是代碼:Kivy(Python)TypeError:預期的字符串或緩衝區

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) 
+0

錯誤消息告訴您哪一行誤差上。 –

+0

什麼是'res'?它是一個字符串嗎?你確定?你檢查過了嗎? [文檔說這是一個字符串列表](https://docs.python.org/2/library/re.html#re.findall)。 –

+0

res是''re.findall(「(\ S +)」,text)''的結果,它是一個數字(int) –

回答

2

我不知道我明白你想達到的(如代碼說的東西比描述不同),但無論哪種方式,您都分配標籤控件作爲文本字符串相對於標籤內容本身(如雅克說過)。

還有一兩件事要記住:彈出內容接受一個小部件(我傳遞標籤下面的答案)

所以你可以做:

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() 

(dirrectly reffering到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() 
+0

第一個解決方案工作!謝謝 :) –

-1

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

分配給可變文字,是一個Label對象而不是一個字符串。對這樣的對象沒有可能的正則表達式搜索。改爲在字符串上使用它。

+0

這就是爲什麼我不能告訴問題在哪裏 –

+0

因此,搜索您的標籤的內容,而不是標籤本身。 –

+0

emm如何? ? ? –

相關問題