Simple Analog Clock in Python 3 Part 4: Updating the Time
HTML-код
- Опубликовано: 20 окт 2024
- Learn how to create a simple analog clock using Python 3 and the turtle module. This tutorial is great for beginners to learn the turtle module and the time module.
NEED HELP?
🆘 Watch this first and then let me know in the comments below: • Help Me Help You
❤️❤️ SHOW SOME LOVE AND SUPPORT THE CHANNEL ❤️❤️
Click Join and Become a Channel Member Today!
Channel members can get preferential comment replies, early access to new content, members only live streams, and access to my private Discord.
❤️ / @tokyoedtech
Amazon Affiliate Links
💻 My Laptop (Asus Zenbook 13): amzn.to/2H3DLbF
🎙My New Microphone (Blue Yeti Pro): amzn.to/2HmjOgN
🎙My Old Microphone (Blue Snowball): amzn.to/3j8magh
🎶My USB Interface (Focusrite Scarlett Solo): amzn.to/3kqyo5m
Other Affiliate Links
⭐ Kite is a free AI-powered coding assistant that will help you code faster and smarter. The Kite plugin integrates with all the top editors and IDEs to give you smart completions and documentation while you’re typing. www.kite.com/g...
LINKS
🗄️ GITHUB: github.com/wyn...
💬 Follow me on Twitter: / tokyoedtech
📜 Subscribe to my Newsletter: eepurl.com/dKgM8k
📝 Check out my Blog: christianthomp...
⬇️ Download Geany Editor: www.geany.org
LEARN MORE PYTHON
➡️Space Invaders: • Python Game Programmin...
➡️Snake Game: • Python Game Programmin...
➡️Pong: • Python Game Programmin...
➡️Space War: • Python Game Programmin...
➡️Intro to Python (for Java Coders): • Intro to Python for Ja...
➡️Space Arena - The Ultimate Python Turtle Graphics Game Tutorial: • Ultimate Python Turtle...
LEARN MORE JAVA
➡️Basic Java for Beginners: • Basic Java 1&2: Commen...
➡️Intro to AP Computer Science A: • AP Computer Science Un...
#Python #Tutorial #Beginner
This is my first visit to your channel. I learned a few new tricks. trace() and update() were new to me. They will be useful in other projects. Well Done!
Welcome! I'm glad you found it helpful. Keep on codin'!
Great tutorial as always! Thanks for heelping us learn programming.
I hated programming in c++/c# at high school. Now I want to learn python for networking and your games are really fun to start. For now I recreate your programs, there will be time for own projects, need to get more familiar with this stuff. Best python channel and teacher.
would doing this:
angle=(h/12)*360+(m/60)*30
angle=(m/60)*360+(s/60)*6
make the hands move smoothly
Olim88
yes ive done the same thing it works amazingly
you are right
olim88
very nice. Thank you
Great content
I discovered your channel a few days ago and I can't stop watching...Keep going (Y)
Very informative series. Thank you for sharing it.
Thanks. Keep on codin'!
For seconds it should be capital S not small s ("%S" not "%s")
@@TokyoEdTech this function of seconds and minute i am unable to apply.. please help me with a different methord.
Hay this is the link of my coding which i had done. Please help drive.google.com/file/d/1M9xhJQHfTVG1G3MpOm-RoOQG63QwUU7i/view?usp=drivesdk
thanks for u suggestion arpit ranjan
@@igniousprogrammerip3536 are you on python 3
@@anupamasingh3520 here is the code
import time
import turtle
wn = turtle.Screen()
wn.bgcolor("black")
wn.setup(width=600, height=600)
wn.title("clock by noah")
wn.tracer(0)
pen = turtle.Turtle()
pen.hideturtle()
pen.speed(0)
pen.pensize(3)
def draw_clock(h, m, s, pen):
pen.up()
pen.goto(0, 210)
pen.setheading(180)
pen.color("green")
pen.pendown()
pen.circle(210)
pen.penup()
pen.goto(0, 0)
pen.setheading(90)
for _ in range(12):
pen.fd(190)
pen.pendown()
pen.fd(20)
pen.penup()
pen.goto(0, 0)
pen.rt(30)
pen.penup()
pen.goto(0, 0)
pen.color("white")
pen.setheading(90)
angle = (h / 12) * 360
pen.rt(angle)
pen.pendown()
pen.fd(100)
pen.penup()
pen.goto(0, 0)
pen.color("blue")
pen.setheading(90)
angle = (m / 60) * 360
pen.rt(angle)
pen.pendown()
pen.fd(150)
pen.penup()
pen.goto(0, 0)
pen.color("red")
pen.setheading(90)
angle = (s / 60) * 360
pen.rt(angle)
pen.pendown()
pen.fd(175)
while True:
h = int(time.strftime("%I"))
m = int(time.strftime("%M"))
s = int(time.strftime("%s"))
draw_clock(h, m, s, pen)
wn.update()
time.sleep(1)
pen.clear()
wn.mainloop()
Thank you as always for your videos!!
One question:
How should one learn concepts behind programming?
Thanks again for the great content, I've subbed and like every video I watch!
Thanks Will - much appreciated!
I actually made a video about this topic - check it out! ruclips.net/video/dRXwSCWZHvc/видео.html
Keep on codin'!
Thank you so much for this series, it was quite helpful and a lot of fun working and tinkering on the clock alongside your videos!
I dunno if I did somethin' weird or not: after all the code was put in, the *wn.mainloop()* that we added earlier (located at the very end of the code) seemed to be redundant (python claimed that that command was actually unreachable), so I just completely lopped that off without issues, whooh. Still works like a charm! :D
Also, looked like if folks still want the animations of the clock face being drawn, the *wn.tracer(0)* line can be moved further down the program - I don't know at which chunk would be best; I had it as the very last line of the last hand-drawing code block we added in, just before the *while True:* block began, and works quite nice-like, it do.
Great tutorial! I did one almost as yours, but added few options.
First, the hour and minute hand doesn't just each hour/minute but goes slowly from an hour to the next/a minute to the next.
Second, it also says the time with numbers.
Finally, I can choose the size of my clock.
Here is the code:
import time
import turtle
# choose size here
size_clock = 300
screen_clock = turtle.Screen()
screen_clock.bgcolor("black")
screen_clock.title("Simple clock by Henri")
screen_clock.setup(width=size_clock/1.5, height=size_clock/1.5)
screen_clock.tracer(0)
# create drawing pen
pen = turtle.Turtle()
pen.hideturtle()
pen.pensize(size_clock/200)
pen.speed(0)
dot = turtle.Turtle()
dot.hideturtle()
dot.color("white")
dot.shape("circle")
dot.shapesize(size_clock/1000)
dot.stamp()
# draw clock
def draw_clock(h, m, s):
pen.penup()
pen.goto(0, size_clock/4)
pen.setheading(180)
pen.color("white")
pen.pendown()
pen.circle(size_clock/4)
pen.penup()
pen.home()
pen.setheading(90)
# hours marks
for i in range(12):
pen.penup()
pen.forward(size_clock/4.8)
pen.pendown()
pen.forward(size_clock/24)
pen.penup()
pen.goto(0, 0)
x = pen.heading()
pen.setheading(x-30)
# minute marks
for i in range(60):
pen.penup()
pen.forward(size_clock/4.28571428571)
pen.pendown()
pen.forward(size_clock/60)
pen.penup()
pen.goto(0, 0)
x = pen.heading()
pen.setheading(x - 6)
# draw hour hand
pen.penup()
pen.home()
pen.color("green")
pen.pensize(size_clock/100)
pen.setheading(90)
angle = (h / 12 + m / 60 / 12 + s / 60 / 60 / 12) * 360
pen.rt(angle)
pen.pendown()
pen.forward(size_clock/10)
# draw minute hand
pen.penup()
pen.home()
pen.color("blue")
pen.pensize(size_clock/100)
pen.setheading(90)
angle = (m / 60 + s / 60 / 60) * 360
pen.rt(angle)
pen.pendown()
pen.forward(size_clock/6.31578947368)
# draw second hand
pen.penup()
pen.home()
pen.color("red")
pen.pensize(size_clock/300)
pen.setheading(90)
angle = (s / 60) * 360
pen.rt(angle)
pen.pendown()
pen.forward(size_clock/5.4545454545)
write = turtle.Turtle()
def write_time(H, M, S, punctuation):
# write the time
write.hideturtle()
write.speed(0)
write.color("white", "grey")
write.setheading(0)
write.penup()
write.setposition(0, size_clock/-8.57142857143)
write.pendown()
writetime = str(H) + punctuation + str(M) + punctuation + str(S)
write.write(writetime, False, align="center", font=("Arial", 13, "normal"))
while True:
h = int(time.strftime("%I"))
m = int(time.strftime("%M"))
s = int(time.strftime("%S"))
H = int(time.strftime("%I"))
M = int(time.strftime("%M"))
S = int(time.strftime("%S"))
#this took me some time to think about
if M < 10:
M = str(0) + str(M)
if S < 10:
S = str(0) + str(S)
write_time(H, M, S, ":")
draw_clock(h, m, s)
screen_clock.update()
time.sleep(1)
pen.clear()
write.clear()
screen_clock.mainloop()
#please tell me if you have anything to add to make it better. Thanks again for the amazing tutorial!
it is still lagy, do you know why??
i am a bit late but this is amazing! thanks for sharing
What a terrific little program you wrote! Thank you for sharing it.
Thanks - glad you liked it!
Excellent lesson thanks. As some others have stated, maybe things have been updated so small-"s" is now a CAPTITAL- "S".
Good call!
Thanks for the video! A great help for beginners!!
Glad it was helpful!
Thank you for doing these
Very nice tutorial!
I also added a loop to draw the minute lines.
Me too
Cool!
Could you make more usefull tutorials like this one? They are awesome. Im improving so fast by washing your videos!
Thanks enormously
Christian Thompson Well tutorials going in dept in different modules for exemple. That would be nice to learn. To be honest, I don’t know anough about python to know what is the next step from here for me...
Thanks dude for making this video ^ ^
I got error at this line s = int(time.strftime("%s"))
I googled it and found %S - second
I corrected it to s = int(time.strftime("%S"))
now it worked well.
@@TokyoEdTech may i ask what software are you using in the video?
@@TokyoEdTech Thanks ^ ^
I'm running my Python editor on Atom and running it through the Mac terminal.
Can you please tell me what this means?
Traceback (most recent call last):
File "analogclock.py", line 77, in
pen.clear()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/turtle.py", line 2642, in clear
self._clear()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/turtle.py", line 2620, in _clear
self.screen._delete(item)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/turtle.py", line 557, in _delete
self.cv.delete(item)
File "", line 1, in delete
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 2511, in delete
self.tk.call((self._w, 'delete') + args)
_tkinter.TclError: invalid command name ".!canvas"
---------
Also, could you briefly explain how you might add numbers at the hour marks?
Christian Thompson Yes, I got it after the program ended. Thanks for the great courses and the prompt reply. I’m hoping for more courses.
To make look hour hand same as real clock i changed
after, angle = (h/12) * 360
added, angle2 = (m/60) * 30
pen.rt (angle+angle2)
"%d assume base 10 while %i auto detects the base" the % mark is the format, in C you always have to write the %s. Like:
int age = 20;
printf("%d", age);
or
const char* name = "Vali";
printf("%s", name);
@
Christian Thompson Absolutely great training exercise for learning Python! Had some problems with indentation at the end of the script, but wiping the slate clean and rewriting four lines did wonders. Do you have an idea how to connect this clock to, I dunno, Google and make it show the real time from a chosen time zone? I'd love to upgrade it to a higher level :3
you can check my code. as it shows the current time: hours, minutes & seconds at your current timezone, but you can change that by importing a different time zone (I think that is possibile) with the datetime module,
my code is here:
pastebin.com/Y18uhXfT
Thanks for your videos
My pleasure.
hay i am not able to make my clock as it is not running on my computer this program
h = int(time.strftime
can you sujjest me me some a different method for updating my clock
How Do U make it so that it moves like a normal analog clock where all the hands are moving , like the second moves in seconds and the minute hand moves not just when the second hand reaches 12 but also when the second hand is moving to 12
and also when the minute hand is moving to 12 the hour hand will also move very slightly ?
How can i make stopwatch?
That darn out-of-scope warning they give for the parameters h, m, s, and pen once they're part of the main loop. That happens to me with a lot of programs, and I can usually fix it with global variable commands, but this one doesn't respond to such a fix. I know globalizing variables is not good practice, but is it good practice to leave parameters as shadows named out of scope? It's only a minor error that doesn't affect the program, but it's a bit nagging. Heh, like me. Excellent tutorial, and I enjoyed how you made a simple clock into something so fun and educational! Nice!
Thanks. Pycharm is a little too overzealous, especially for beginners. My students have a really hard time with scope - it's better to introduce it later.
@@TokyoEdTech It is definitely overzealous. While it soothes my compulsiveness in some ways by making sure I clean up my code, and thus acting as a sort of teacher, it' also can be quite a pain in the arse. So yeah... I'll worry about the scope stuff later! Thanks again for all your awesome videos! I'm leaving no stone unturned!
ok I just noticed this tutorial, wrote it, ran it, good stuff....question, can you give us a few lines to make it so when the clock starts it uses the Current GMT as a starting point? or is that too tricky?.
when I say GMT I actually mean my local time..which is GMT +10. lol
ohh I just realised, it does start at your local time..how nifty!
I think it works by checking the computer time - all good!
Can you make it so you have the animation a little longer? because it looked cool!
You might be able to play with wn.tracer() to get the speed you want.
Great Work!
Sir, would you please make video python from beginning to advance. because your teaching very good 🙏🙏🙏🙏 fast understand
Mr Christian Thompson thank you so much, i wanna be your student, its my email noverizaperi@gmail.com
when it got to the 'I, M, S' part it kept showing up as not responding is that because of my computer being too slow!
what does pen.fd(190) mean ? should it be 180.
Fd=forward
The clock in pycharm is a little bit slower. it is behind 1 second from the actual clock. But thanks for posting such posts
You're welcome.
Well made program dude
but there is a error showing in my program:
s = int(time.strftime("%s"))
ValueError: Invalid format string
what to do plz reply
Thanks. Try capital S instead.
Every time I run the code I get:
invalid command name ".!canvas"
I think it's because I'm not exiting the loop before closing the window, but I've tried exiting the loop with "break" and pygame events but I can't get it to work without the error message and it's really annoying me. Any advice?
Also I love your community :)
To solve it, put "try:" at the start of your code, then put
"except Exception:
quit"
without the "
I wanted the code,is the GitHub code available, the link doesn't exist anymore
Sorry - I can't find a link to the code either.
I get this error and it is just a black window can somebody help?
h = int(time.strftime("%1"))
ValueError: Invalid format string
I think it is %h, not %1.
The second hand doesn't work for me, i think its because I'm using Python 3.8.3...
It is unlikely that is the problem - it is far more likely there is an error in your code, or mine.
the search box in your website is not working think so
@@TokyoEdTech ok
How do I get my timezone? I'm running Python 3.8 and it's giving me UTC time.
# Simple Analog Clock in Python 3
# by @TokyoEdTech
import turtle
import time
wn = turtle.Screen()
wn.bgcolor("black")
wn.setup(width=600, height=600)
wn.title("Simple Analog Clock by Chris Albright")
wn.tracer(0)
# Create our drawing pen
pen = turtle.Turtle()
pen.hideturtle()
pen.speed(0)
pen.pensize(3)
def draw_clock(h, m, s, pen):
# Draw Clock Face
pen.up()
pen.goto(0, 210)
pen.setheading(180)
pen.color("Green")
pen.pendown()
pen.circle(210)
# Draw the lines for the hours
pen.penup()
pen.goto(0, 0)
pen.setheading(90)
for _ in range(12):
pen.fd(190)
pen.pendown()
pen.fd(20)
pen.penup()
pen.goto(0, 0)
pen.rt(30)
# Draw the hour hand
pen.penup()
pen.goto(0, 0)
pen.color("white")
pen.setheading(90)
angle = (h/60)*360+(m/60)*30
pen.rt(angle)
pen.pendown()
pen.fd(100)
# Draw the minute hand
pen.penup()
pen.goto(0, 0)
pen.color("blue")
pen.setheading(90)
angle = (m/60)*360+(m/60)*6
pen.rt(angle)
pen.pendown()
pen.fd(150)
# Draw the Second hand
pen.penup()
pen.goto(0, 0)
pen.color("red")
pen.setheading(90)
angle = (s/60)*360
pen.rt(angle)
pen.pendown()
pen.fd(200)
while True:
h = int(time.strftime("%I"))
m = int(time.strftime("%M"))
s = int(time.strftime("%S"))
draw_clock(h, m, s, pen)
wn.update()
time.sleep(1)
pen.clear()
wn.mainloop()
Sorry, not sure. Check the time module docs.
It worked but not in my computer it just hangs and doesn't respond XD but thanks!!
Yw.
So can I do it without the while loop?
after i use the while looop, the output window showing the clock does not respond
and everything is just black
pastebin.com/uj6DQhu5
C:\Users\User\PycharmProjects\untitled12\venv\Scripts\python.exe C:/Users/User/PycharmProjects/untitled12/regression.py
Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/untitled12/regression.py", line 72, in
pen.clear()
File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\turtle.py", line 2642, in clear
self._clear()
File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\turtle.py", line 2620, in _clear
self.screen._delete(item)
File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\turtle.py", line 557, in _delete
self.cv.delete(item)
File "", line 1, in delete
File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 2508, in delete
self.tk.call((self._w, 'delete') + args)
_tkinter.TclError: invalid command name ".!canvas"
Thank you brother. You are the BEST
#import time also done
#Everything works fine above this line of code
#For updating time
while True:
h=int(time.strftime("%I"))
m=int(time.strftime("%M"))
s=int(time.strftime("%s"))
make_circle(h,m,s,pen)
BUT THE ERROR IS:
C:\myenv\Scripts\python.exe C:/Users/Dell/.PyCharmCE2018.2/config/scratches/scratch_2.py
Traceback (most recent call last):
File "C:/Users/Dell/.PyCharmCE2018.2/config/scratches/scratch_2.py", line 71, in
s=int(time.strftime("%s"))
ValueError: Invalid format string
Process finished with exit code 1
hey, great work but I am having an error with "%I"
ValueError: time data '%I' does not match format '%a %b %d %H:%M:%S %Y'
Please help
@@TokyoEdTech Traceback (most recent call last):
File "C:/Users/akjsa/PycharmProjects/Video/final.py", line 69, in
h = int(time.strptime("%I"))
File "C:\Users\akjsa\AppData\Local\Programs\Python\Python37-32\lib\_strptime.py", line 571, in _strptime_time
tt = _strptime(data_string, format)[0]
File "C:\Users\akjsa\AppData\Local\Programs\Python\Python37-32\lib\_strptime.py", line 359, in _strptime
(data_string, format))
ValueError: time data '%I' does not match format '%a %b %d %H:%M:%S %Y'
@@TokyoEdTech pastebin.com/Sqmk9yYf
@@TokyoEdTech Thank You so much, it is actually working
last thing how do we get to print the time at the bottom
I am got an error as follows
s = int(time.strftime("%s"))
ValueError: Invalid format string
I got error as above can u please help me out*
yeah i tried but it is not showing second_hand itself.
I am using python 3.6
yeah i got.. thank u Christian Thompson
7:28 You don't need time.sleep because it updates to the current time not the next second
Thanks for the tip!
pls send the complete code
Do you know how to make game bots ? Can you teach?
really good teacher btw
@@TokyoEdTech Sentdex actually has a tutorial on GTA V autodrive bot with collision detection IIRC. He's doing things fast, but he's equally great at showing how to code and solve problems with code c:
3.30
h = int(time.strftime("%I"))
# I has to be here for hours,
#M for minutes and
#putting s small gives error. s should be capital.
m = int(time.strftime("%M"))
s = int(time.strftime("%S"))
3:28 nope … cap S
Oops!
Great tutorial as always!
I've tried to do this by myself without looking at your code (except the circle drawing) and I've made it! it works awsome and smooth, here is the code (python3.7):
pastebin.com/Y18uhXfT
I forgot to add to my code a line that makes the HOUR_HAND move in between hours, for example if the hour is 3:30 the hour hand should point in between 3 and 4, so to do that change the following:
angle = (h / 12) * 360 (LINE 81)
to:
angle = (h / 12) * 360 + (0.5 * m)
Thank you so much!