如何在画布文本中添加 Tkinter 文本变量 [英] How to add a Tkinter Text Variable in canvas text
问题描述
我正在尝试制作一个基本的天气小部件,其中一些文本覆盖了图片.文本是当前温度,图像是外部天气的表示,例如:阴天、晴天……为了掌握天气,我使用了 Python Weather API
I am trying to make a basic weather widget where some text overlays a picture. The text being the current temperature, the image being a representation of the weather outside eg: Cloudy, Sunny... To get hold of the weather, I am using the Python Weather API
import pwapi
我已将温度保存为变量.
I have the temperature saved to variable.
var = StringVar(root)
var.set(temperature)
我使用 if 语句来确定要显示的图像.但是,我的问题出在这里:
I have used if statements to determine which image to display. However, my problem lies here:
weather_canvas.create_text(135, 130, textvariable=var, font=("Courier New", 70),)
当我收到此错误时,画布文本似乎无法显示变量:
It seems that canvas text cannot display variables as I get this error:
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"
我该怎么做?
推荐答案
在 StringVar 上使用跟踪:
Use a trace on the 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()
或者,您可以只使用标签小部件并利用复合选项.
Alternatively, you could just use a Label widget and take advantage of the compound option.
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()
这篇关于如何在画布文本中添加 Tkinter 文本变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!