Photoimage在新窗口中没有显示 - 使用Python tkinter [英] Photoimage not displying in new window - using Python tkinter

查看:234
本文介绍了Photoimage在新窗口中没有显示 - 使用Python tkinter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个要求输入字符串和代码的程序,并打开一个新窗口并显示字符串,如LED文本。现在,为了测试它,我已经用新窗口绘制窦的方式写了它,但它没有显示。虽然在LED类的__init__函数中运行代码运行良好。



我尝试过:



I`m writing a program which asks for a string and code, and opens a new window and shows the string like a LED Text. for now, to test it, I have written it in a way that new window draws a sinus but it`s not shown. While running the code in __init__ function of LED class works well.

What I have tried:

from Tkinter import *
import time
from math import sin
STEPTIME = 0.50
WIDTH = 200
HEIGHT = 20
class App:
	def __init__(self, master):
		#Initialize Data Panel
		self.dataFrame = Frame(master)
		self.stringLabel = Label(self.dataFrame, text="Enter a string: ")
		self.stringBox = Text(self.dataFrame, height=1, width=30)
		self.codeLabel = Label(self.dataFrame, text="Enter display code: ")
		self.codeBox = Text(self.dataFrame, height=1, width=5)
		self.dataFrame.pack(padx=5 ,pady=10 , side=LEFT)
		self.stringLabel.pack()
		self.stringBox.pack()
		self.codeLabel.pack()
		self.codeBox.pack()
		
		#Initialize Button panel
		self.buttonFrame = Frame(master)
		self.button = Button(self.buttonFrame, text="Run", command=self.run)
		self.buttonFrame.pack(padx=5 ,pady=20 , side=RIGHT)
		self.button.pack()

	def run(self):
		string = self.getString()
		code = self.getCode()
		root = Tk()
		led = LED(root)
		root.mainloop()
		
	def getString(self):
		string = self.stringBox.get("1.0", "end-1c")
		return string
		
	def getCode(self):
		code = self.codeBox.get("1.0", "end-1c")
		return code
		
class LED:
	def __init__(self, master):
		WIDTH, HEIGHT = 200, 200
		canvas = Canvas(master, width=WIDTH, height=HEIGHT, bg="#000000")
		canvas.pack()
		img=PhotoImage(master = canvas, width=WIDTH, height=HEIGHT)
		canvas.create_image((WIDTH/2, HEIGHT/2), image=img, state="normal")
		for x in range(4 * WIDTH):
			y = int(HEIGHT/2 + HEIGHT/4 * sin(x/80.0))
			img.put("#ffffff", (x//4,y))
		
root = Tk()
app = App(root)
root.mainloop()

推荐答案

问题是由 img 对象在<$ c $之后被垃圾收集的事实引起的c> LED .__ init __ 方法已完成,因此画布显示为空白。添加类似下面的额外行的东西就可以了。

The problem was caused by the fact that the img object was being garbage collected after the LED.__init__ method completed, so the canvas appeared blank. Adding something like the extra line below holds it in place.
img=PhotoImage(master = canvas, width=WIDTH, height=HEIGHT)
canvas.create_image((WIDTH/2, HEIGHT/2), image=img, state="normal")
canvas.theimage = img # add attribute to prevent GC


这篇关于Photoimage在新窗口中没有显示 - 使用Python tkinter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆