我正在尝试创建一个基本天气小部件,其中一些文字覆盖图片。文本是当前的温度,图像是外面天气的代表,例如:多云,晴天...... 为了掌握天气,我正在使用Python Weather API
import pwapi
我将温度保存为变量。
var = StringVar(root)
var.set(temperature)
我使用if语句来确定要显示的图像。但是,我的问题在于:
weather_canvas.create_text(135, 130, textvariable=var, font=("Courier New", 70),)
似乎画布文本无法显示变量,因为我收到此错误:
Traceback (most recent call last):
File "C:/Users/Charlie/Desktop/Project Files/Weather API/Canvas.py", line 25, in <module>
weather_canvas.create_text(135, 130, textvariable=var, font=("Courier New", 70),)
File "C:\Python34\lib\tkinter\__init__.py", line 2342, in create_text
return self._create('text', args, kw)
File "C:\Python34\lib\tkinter\__init__.py", line 2318, in _create
*(args + self._options(cnf, kw))))
_tkinter.TclError: unknown option "-textvariable"
我该怎么做?
答案 0 :(得分:0)
在StringVar上使用跟踪:
from tkinter import *
root = Tk()
s = StringVar(root, '23.1')
# your image here
image1 = PhotoImage(width=200, height=200)
image1.put('blue', to=(0,0,199,199))
canvas = Canvas(root, width=300, height=300)
canvas.pack()
canvas.create_image(150,150, anchor='c', image=image1)
txt = canvas.create_text(150,150, font='Helvetica 24 bold', text=s.get())
def on_change(varname, index, mode):
canvas.itemconfigure(txt, text=root.getvar(varname))
s.trace_variable('w', on_change)
def trigger_change():
s.set('26.0')
root.after(2000, trigger_change)
root.mainloop()
或者,您可以使用Label小部件并利用复合选项。
from tkinter import *
root = Tk()
s = StringVar(root, 'fine')
image1 = PhotoImage(width=200, height=200)
image1.put('blue', to=(0,0,199,199))
image2 = PhotoImage(width=200, height=200)
image2.put('gray70', to=(0,0,199,199))
lbl = Label(root, compound='center', textvariable=s, image=image1)
lbl.pack()
def trigger_change():
lbl.config(image=image2)
s.set('cloudy')
root.after(2000, trigger_change)
root.mainloop()