How to make an interactive simple watch in python? - python

I'm a bit confused with how to create a watch in python
I wrote the follow code:
from Tkinter import *
root = Tk()
tt='vv'
def time(tt):
from time import strftime
tt=strftime('%H:%M:%S')
return tt
Label= Label(root,bd=11,text=time(tt))
Label.pack()
root.mainloop()
How may I make it interactive? now it just shows the time which was at the moment of running program

You can use the after function to schedule a method call.
Here's a little example. Note that I am using a StringVar to easily set the text of the Label.
from Tkinter import *
from time import strftime
root = Tk()
time_var = StringVar()
def set_time():
time_var.set(strftime('%H:%M:%S'))
root.after(1000, set_time)
Label(root, bd=11, textvariable=time_var).pack()
set_time()
root.mainloop()
I call set_time once, and then set_time schedules itself to be called every 1000 ms.

Related

how to cancel to call the function in python tkinter?

I am creating a reminder application in python using the Tkinter module. I need to cancel to call the function when the user clicks on the cancel remind button. I tried to assign the time (time variable that contains the time in milliseconds when the function will call) variable to 0, but it does not work.
sorry,for late respond i was creating small example this is the smallest example i can create.
code:
# example:
from tkinter import Tk, mainloop, TOP
from tkinter.ttk import Button
time=10000
# creating tkinter window
root = Tk()
def function_to_cancel():
global time
time=0 # not works
button = Button(root, text = 'Remind Me! after 10 seconds')
button.pack(side = TOP, pady = 5)
cancel=Button(root,text='Cancel Remind',command=function_to_cancel)#this button will cancel the remind
cancel.pack()
print('Running...')
root.after(time, root.destroy)
mainloop()
If you understand the question, please answer.
You need to save the task ID returned by .after() and then use the ID with .after_cancel() to cancel the scheduled task:
from tkinter import Tk, mainloop, TOP
from tkinter.ttk import Button
time=10000
# creating tkinter window
root = Tk()
def function_to_cancel():
#global time
#time=0 # not works
root.after_cancel(after_id)
button = Button(root, text = 'Remind Me! after 10 seconds')
button.pack(side = TOP, pady = 5)
cancel=Button(root,text='Cancel',command=function_to_cancel)#this button will cancel the remind
cancel.pack()
print('Running...')
# save the ID returned by after()
after_id = root.after(time, root.destroy)
mainloop()

Perform multi-threading on a python program

I want to execute 2 function in the same time,
(im new in python, and development in general)
i tried to create a minecraft server setup assistant :
(the code is in development too)
import os
import tkinter as tk
from tkinter import ttk
import threading
import wget
import json
from pathlib import Path
...
def startndstop(x):
os.chdir(newpath)
if x == "start":
start = str("java" + ram() + namejar + " nogui")
print("Demarrage du serveur", name, "!")
os.system(str(start))
elif x == "stop":
os.system("stop")
root = tk.Tk()
root.title("Yann Installer")
root.iconbitmap("./minecraft_icon_132202.ico")
root.geometry("640x390")
root.resizable(width=False, height=False)
root.configure(bg="#0f800f")
bgimage = tk.PhotoImage(file="background.gif"))
l = tk.Label(root, image=bgimage)
l.pack()
installbutton = tk.Button(root, text="Installer", command=lambda :threading.Thread(target=install("1.8.3")).start())
installbutton.lift(aboveThis=l)
installbutton.place(x=10, y=10)
startbutton = tk.Button(root, text="Demarrer", command=lambda :threading.Thread(target=startndstop("start")).start())
startbutton.lift(aboveThis=l)
startbutton.place(x=10, y=40)
listeVersion = ttk.Combobox(root, values=versionlist())
listeVersion.current(0)
listeVersion.lift(aboveThis=l)
listeVersion.place(x=80, y=10, width=100)
threading.Thread(target=root.mainloop).start()
threading.Thread(target=startndstop,args=('start',)).start()
But when I execute the script , the second thread start only when i close the tkinter window.
edit: now the function are called correctly
Could you help me ?
Thread is not being called correctly. You are calling root.mainloop() and passing its return value to the threads as target, requiring it to run to completion in order to return. Instead, pass the function object itself as target by removing the parentheses. The second thread has the same issue, but needs to pass arguments as a separate args tuple.
Use this:
threading.Thread(target=root.mainloop).start() # start the tkinter interface
threading.Thread(target=startndstop,args=("start",)).start() # start the minecraft server

Why there is a problem while displaying image from different a GUI in different module by making call to the function from another module?

I tried to make a module in which I made a funtion which just reads and display the image in GUI. Then I made another module which makes call to that function when the button is clicked. Button gives me error.
#module code:
from tkinter import *
class disp:
def __init__(self):
root1.geometry("400x500")
image = PhotoImage(file = 'png2.png')
Label(root1,image=image).pack()
root1.mainloop()
#main code:
from tkinter import *
import testimg as ti
def click():
ti.disp()
root = Tk()
Button(text = 'Click me',command=click).pack()
root.mainloop()
In your class disp, you have put the master as root1 whereas in the main code, you have defined Tk() as root. This means that root1 is no window so the label that has a master of root1 has no where to pack itself.
You also need to remove root1.mainloop() because it’s useless and causing errors due to the fact that root1 doesn’t have Tk(). It’s like trying to loop a while statement without typing in while. This gives an error.
Below modified code is based on yours:
#module code:
from tkinter import *
class disp:
def __init__(self):
root1 = Tk()
root1.geometry("400x500")
image = PhotoImage(master=root1, file='png2.png') # set master to root1
Label(root1, image=image).pack()
root1.mainloop()
But using multiple Tk() instances is not a good design.

Update Tkinter panel over time

I have Tkinter panels that I want to update over time. The main file executes a method on an imported class to draw the Tkinter panel and I want it to execute 5 times every second.
Here is the main script which calls the method to create the panel:
# Script to control updating the display
from tkinter import *
from settings import Settings
from main_panel import Main
import time
# Creates window
root = Tk()
root.configure(background = 'black')
# Establish settings variable
settings = Settings()
# Create panel class with settings
Main = Main(settings)
# Call panel function to create itself
Main.create(root)
root.mainloop()
Here is the method which creates the Tkinter panels:
def create(self,root):
current = self.get_current_status()
self.draw_icons(root,current)
self.draw_days(root,current)
self.draw_temps(root,current)
self.draw_status(root,current)
Where do I do the 'root.after' call to have the panels update?
You've not provided enough code for a customized example, so here's a minimalist example of using root.after():
from tkinter import *
def update_counter():
counter = label_variable.get()
if counter > 0:
label_variable.set(counter - 1)
root.after(1000, update_counter)
root = Tk()
label_variable = IntVar()
label_variable.set(10)
Label(root, textvariable=label_variable, width=10).pack()
root.after(1000, update_counter)
root.mainloop()
Hopefully this will give you an idea of how to incorporate root.after() into your own code.

Make tkinter label refresh at set time intervals without input

I've been trying for the past couple of hours to find a way to refresh a label with information without having to input anything myself.
The program I am trying to write is taking the CPU temp from the Raspberry Pi and displaying it in a window. I need to make that temp input to update every 5 seconds or so, but all attempts to do so have failed.
I tried while loops and found that they do not work inside tkinter, and I can't think how to refresh something constantly without input without one.
I am quite new to Python so I'm sure there is a way and I just haven't come across it yet. Similar questions on here don't quite lead to an answer that applies for me.
Here is my bit of code right now:
import subprocess
from tkinter import *
root = Tk()
root.title('CPU Temp')
cpuLab = Label(root, text = 'CPU Temp:',
font =('Nimbus Mono L',14,),
bg = 'black', fg = 'green').grid(row = 0, column = 0)
cpuTemp = subprocess.check_output(['/opt/vc/bin/vcgencmd', 'measure_temp'])
cpuVar = StringVar()
cpuDisplay = Label(root, textvariable = cpuVar,
font =('Nimbus Mono L',14),
bg = 'black', fg = 'green').grid(row = 0, column = 1)
cpuVar.set(cpuTemp[5:11])
root.mainloop()
This works perfectly for showing the temperature, it just has to be rerun in order to refresh.
Tkinter root windows have a method called after which can be used to schedule a function to be called after a given period of time. So call that function itself like (you will have to create a class first):
def update_label(self):
self.label.configure(cpuTemp)
self.root.after(1000, self.update_label)
This will then reload your label every second.
This may help you: Creating a Timer with tkinter
TKINTER
Refresh, Update, Rerender
This code works for any type of Tkinter widget update
#!/usr/bin/env python3
import sys
import time
from tkinter import *
# Global variables
running = True
# Button action updater
def callback():
if button_1["state"] == "disabled":
button_1["state"] = "normal"
else:
button_1["state"] = "disabled"
root.after(4000, callback)
# Window setup
root = Tk()
root.title("Buttons")
root.geometry("400x300")
# Buttons setup
button_1 = Button(root, text="Learn Python", command=callback)
button_1.pack()
# Software loop
root.mainloop()
Python version used to created this software is: >=3.x

Categories

Resources