【问题标题】:Kivy Weather App How to Print Output to label?Kivy Weather App 如何打印输出到标签?
【发布时间】:2020-02-18 06:26:00
【问题描述】:

我正在尝试弄清楚如何将tellweather()类中的天气结果打印到kivy中的文本标签中。但它不起作用错误: TypeError: __init __ () 接受 1 个位置参数,但给出了 2 个。通常结果是“它的 24 Temp”。我现在有以下代码:

import kivy
import requests
import json
from kivy.app import App
from kivy.uix.label import Label 
class tell_weather():
    url ='http://api.openweathermap.org/data/2.5/weather?q=appid=xxxxxx"'     
    json_data = requests.get(url).json()     
    format_add = json_data['main']['temp'] 
    print("Its", format_add, "Temp")

    kivy.require("1.9.1") 

class MyLabelApp(App): 
    def build(self):
        label display the text on screen 
            lbl = Label(tell_weather())
        #lbl = Label(tellweather())
        return lbl 

    # creating the object 

label = MyLabelApp() 
label.run() 


【问题讨论】:

  • 必须查看其余代码,但我怀疑您的__init__ 中可能没有self 设置,或者您的 args 排序不正确,如果它遵循父类__init__ 结构。只是一些提示,希望对您有所帮助:)
  • 嗯,这是我的完整代码 -_- 它是 kivy 和 python 的新手 :(

标签: python kivy


【解决方案1】:

标签以另一种方式工作,将文本放在那里你应该使用参数'text',所以你的代码应该是这样的:

# it's not a class, it's a function!
def tell_weather():
    url ='http://api.openweathermap.org/data/2.5/weather?q=appid=xxxxxx"'     
    json_data = requests.get(url).json()     
    format_add = json_data['main']['temp'] 
    # print makes output to console, it's wrong, here you should return string
    return("Its " + str(format_add) + " Temp")

class MyLabelApp(App): 
    def build(self):
        # what's that line doing here? Comment it!
        # label display the text on screen 

            # so here we use text parameter that will be equal to string that function tell_weather returns
            lbl = Label(text=tell_weather())
        return lbl

【讨论】:

  • 谢谢@Lothric 现在我明白了这个问题。谢谢!!现在我得到这个错误: TypeError: can only concatenate str (not "float") to str 这是什么意思?非常感谢你:)
  • @Smugmug _NOD 您应该将 format_add 转换为字符串。我已经编辑了我的答案,检查一下。
  • 谢谢你的英雄!
猜你喜欢
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-01
  • 1970-01-01
相关资源
最近更新 更多