I just wrote a simple clicker counter in python using the turtle module. When I run it the number just flashes over and over again, otherwise it works fine.
I've used .tracer() and .update() in any way I could think of as well as tried .mainloop(). I believe the problem is in my usage of .clear() however I have no idea how to fix this.
import turtle
num = 0
def counting(x, y):
global num
num += 1
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("Clicker")
wn.screensize(600, 600)
wn.setup(650, 650, starty=15)
wn.tracer(10)
count = turtle.Turtle()
count.hideturtle()
count.color("white")
count.speed(0)
wn.onscreenclick(counting)
while True:
wn.update()
count.write(num, False, align="center", font=("Arial", 100, "bold"))
count.clear()
Thanks for everyone's help.
For similar projects, I added a conditional to the loop to only update if the value changes.
while True:
old_num = num
wn.update()
if (old_num != num):
count.write(num, False, align="center", font=("Arial", 100, "bold"))
count.clear()
This is simpler to do than you're making it. Rather than clear()
, I recommend undo()
for this sort of text update application (eg the score in a game, a timer, etc.) Move a dedicated turtle to where the text goes, write an initial (zero) value, and when you want a new value, do a combination of undo()
and write()
:
from turtle import Screen, Turtle
FONT = ('Arial', 100, 'bold')
num = 0
def counting(x, y):
global num
num += 1
count.undo() # undo previous write()
count.write(num, align="center", font=FONT)
wn = Screen()
wn.bgcolor('black')
wn.title("Clicker")
wn.setup(650, 650, starty=15)
count = Turtle(visible=False)
count.color("white")
count.write(num, align="center", font=FONT)
wn.onscreenclick(counting)
wn.mainloop()
(The turtle undo feature was added in Python 3.) An event-based environment like turtle should never have a while True:
in control -- it potentially blocks events you want. You should set up all your event handlers and turn control over to the main event loop via mainloop()
or one of its variants. Also, avoid tracer()
unless you fully understand what it does and you've already got working code that needs optimizing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.