How to add a Tkinter Text Variable in canvas text

百般思念 提交于 2019-12-12 01:54:49

问题


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) 

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"

How would I go about this?


回答1:


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


来源:https://stackoverflow.com/questions/28518976/how-to-add-a-tkinter-text-variable-in-canvas-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!