在我在下面发布的程序中,用户可以点击使用特定颜色绘制的圆圈。根据圆圈是黄色还是蓝色,文本将显示在与"正确"相同的窗口中。或"不正确"。我遇到的问题是在用户点击文本将显示的圆圈后,但在第一次尝试后,窗口中的文本将保留,导致每次后续点击的不幸问题导致新文本写入以前显示的文字。如果有人知道如何将文本转换为"重置"或"清除"那是在窗口中,所以每次用户点击时窗口都会是空白的,我会很感激。感谢
from graphics import *
import tkinter as tk
import threading
import random
class App():
def __init__(self):
self.win = GraphWin('Demo2', 800, 600) # give title and dimensions
self.th = threading.Thread(target=self.FlashThread, daemon=False)
def FlashThread(self):
while not self.win.isClosed():
count = random.randint(0, 8)
t = threading.Timer(1.0, self.flash, [count])
t.start()
t.join()
def flash(self, count):
try:
diameter = 50
centers = ((55,55), (170,55), (285,55), (55,170), (170,170),
(285,170), (55,285), (170,285), (285,285))
circles = list()
for point in centers:
c = Circle(Point(point[0], point[1]), diameter)
circles.append(c)
c.setFill("blue")
c.draw(self.win)
circles[count].setFill("yellow")
mouseClick = self.win.getMouse()
correctMessage = Text(Point(self.win.getWidth()/2, 20), 'Correct!')
incorrectMessage = Text(Point(self.win.getWidth()/2, 20), 'Incorrect,Try Again')
leftX = centers[count][0] - diameter
rightX = centers[count][0] + diameter
upperY = centers[count][1] - diameter
lowerY = centers[count][1] + diameter
if (upperY < mouseClick.y < lowerY) and (leftX < mouseClick.x < rightX):
correctMessage.draw(self.win)
else:
incorrectMessage.draw(self.win)
except:
self.win.exit(0)
if __name__ == "__main__":
try:
app = App()
app.th.start()
app.win.mainloop()
app.th.join()
finally:
app.th.close()
app.close()
答案 0 :(得分:0)
您可以使用undraw()
方法执行此操作。将您的__init__
更改为:
def __init__(self):
self.win = GraphWin('Demo2', 800, 600) # give title and dimensions
self.th = threading.Thread(target=self.FlashThread)
self.correctMessage = Text(Point(self.win.getWidth()/2, 20), 'Correct!')
self.incorrectMessage = Text(Point(self.win.getWidth()/2, 20), 'Incorrect,Try Again')
和flash
到
def flash(self, count):
try:
self.correctMessage.undraw()
self.incorrectMessage.undraw()
diameter = 50
centers = ((55,55), (170,55), (285,55), (55,170), (170,170),
(285,170), (55,285), (170,285), (285,285))
circles = list()
for point in centers:
c = Circle(Point(point[0], point[1]), diameter)
circles.append(c)
c.setFill("blue")
c.draw(self.win)
circles[count].setFill("yellow")
mouseClick = self.win.getMouse()
leftX = centers[count][0] - diameter
rightX = centers[count][0] + diameter
upperY = centers[count][1] - diameter
lowerY = centers[count][1] + diameter
if (upperY < mouseClick.y < lowerY) and (leftX < mouseClick.x < rightX):
self.correctMessage.draw(self.win)
else:
self.incorrectMessage.draw(self.win)
except:
self.win.exit(0)