Python running clock in separate window - python

I thought I would make a running clock program. I have this code which works for what I want it to do, but I want it to be fancy and output it to a new window. I thought of a message box but that would need constant closing.
Is there way around this, or should I just stick to using the console?
x=0
import datetime
import time
while x<10:
currentTime=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
time.sleep(1)
print(str(currentTime))
EDIT:
This is what i have now but the window goes all over the place.
try:
from Tkinter import *
except ImportError:
from tkinter import *
import datetime
import time
x=0
while x<10:
root = Tk()
prompt = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
label1 = Label(root, text=prompt, width=len(prompt))
label1.pack()
def close_after_1s():
root.destroy()
root.after(1000, close_after_1s)
root.mainloop()

You're missing the point of Tk. The entire thing is a loop(hence the mainloop) and you keep destroying and creating a new window, hence the all over the place.
I think you just want something to update every sec:
from Tkinter import Tk,StringVar,Label
import datetime
def update():
global prompt,root
prompt.set(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
root.after(1000, update)
root = Tk()
prompt = StringVar()
label1 = Label(root, textvar=prompt, width=len(prompt.get()))
label1.pack()
update()
root.mainloop()
and my suggestion is to put all of this in a class. Google some Tk examples.

Related

Firstly I want to place label1 and after 3 seconds i want to configure background but it doesnt work

import tkinter as tk
import time
root=tk.Tk()
label1=tk.Label(text='hello',font='Calibri 25')
label1.pack()
time.sleep(3)
label1.configure(bg='green')
root.mainloop()
Again and again I say only I want to place label1 and after 3 seconds I want to change the background color but it doesnt work. Can you explain me the main problem and what can I do?
sleep should not be used in the main tkinter loop, as this causes the interface to freeze. It's better to use after.
import tkinter as tk
COLOR = 'green'
def lbl_clear():
label1.configure(text="", bg=root['bg'])
def lbl_bg(color):
label1.configure(bg=color)
root.after(3000, lbl_clear)
root = tk.Tk()
label1 = tk.Label(text='hello', font='Calibri 25')
label1.pack()
root.after(3000, lbl_bg, COLOR)
root.mainloop()

How to trigger again a callback function before the first call for that function has ended

Good morning,
What I am aiming for:
I want to create a button that when clicked triggers a call back function (even if that function is still running).
Module:
I am using tkinter
Problem:
When I trigger the button, the function runs, but then I cannot push the button again before the function has finished its run. I want to be able to push the button while the function is still running and have the function stop and run again from start.
My attempts:
I tried both a procedural and a OOP approach: both present the same problem
My attempt n1: Procedural approach
import time
import tkinter as tk # Import tkinter
from tkinter import ttk # Import ttk
def func():
for i in range (100):
print(i)
time.sleep(5)
win = tk.Tk() # Create instance of the Tk class
aButton = ttk.Button(win, text="Click Me!", command=func)
aButton.grid(column=0, row=0) # Adding a Button
win.mainloop() # Start GUI
My attempt n2: OOP approach
import time
import tkinter as tk # Import tkinter
from tkinter import ttk # Import ttk
class OOP():
def func(self):
for i in range (100):
print(i)
time.sleep(5)
def __init__(self):
win = tk.Tk() # Create instance of the Tk class
aButton = ttk.Button(win, text="Click Me!", command=self.func)
aButton.grid(column=0, row=0) # Adding a Button
win.mainloop() # Start GUI
oop = OOP()
Thanks
In tkinter, as with most GUI frameworks, there is a for loop running somewhere that constantly checks for user input. You are hijacking that loop to do your func processing. Tkinter can not check for user input, nor e.g. change the appearance of the button icon, because there is only one thread and you are using it.
What you will want to do is fire up a thread or process to do the work. There are lots of libraries to do parallel processing in elaborate ways if you have lots of background tasks but this will do for a single function (see also this answer).
import time
import tkinter as tk # Import tkinter
from tkinter import ttk # Import ttk
import threading
def button():
thread = threading.Thread(target=func, args=args)
thread.start()
def func():
for i in range (100):
print(i)
time.sleep(5)
win = tk.Tk() # Create instance of the Tk class
aButton = ttk.Button(win, text="Click Me!", command=button)
aButton.grid(column=0, row=0) # Adding a Button
win.mainloop() # Start GUI
If the process is long running, you might need to find a way to clean up the threads when they're done.

Tkinter Text closes but ipython console keeps running indefinetly

I am trying to print some rows of a pandas dataframe for the user of my tkinter GUI. However, in this test, the tk window is showed, but when closed, the code stop running.
import pandas as pd
import numpy as np
import sys
from tkinter import *
dates = pd.date_range('20160101', periods=6)
df = pd.DataFrame(np.random.randn(6,4),index=dates,columns=list('ABCD'))
root = Tk()
t1 = Text(root)
t1.pack()
class PrintToT1(object):
def write(self, s):
t1.insert(END, s)
sys.stdout = PrintToT1()
print ('Hello, world!')
print (df)
mainloop()
root.destroy()
print(2)
I am running the script in Spyder, and when I close the window, the ipython console continues processing something, but it never reaches the last line to print the number 2, and I have to restart the console manually.
I want it to close the tk window and continues the script, since in the GUI, after closing the tk window, the code will have to do some calculations for the user. How could I do this?
picture
I am new here (page) but the error is that the mainloop is a loop itself If you close the window the program closes.
root_window.mainloop()
#destroy()use in ithems or daughters windows
test add:
def date_name(self):
t3 = Toplevel(root)
t3.geometry('240x100+20+20')
t3.title("...")
t3.destroy()#use valid
The sample of the data in that window and the function destroy ().
Find how to use the Canvas and the Frame if you want to request the data from the same window but the fields of texts and buttons belong to the cambas ... well I work like that in tkinter.
canvas_menu = Canvas(root, width=200, height=200)
canvas_menu.destroy()#this use valid
root.destroy not valid Tk()is a funcion.
test:
from tkinter import *
from tkinter import ttk
root=Tk()
def new_window():
t3 = Toplevel(root)
t3.geometry('240x100+20+20')
t3.title("...")
Label(t3,text="I hope to help you").pack()
Button(t3,text="destroy() in t3 ",command=t3.destroy).pack()
canvas_c=Canvas(root, width=400, height=400)
canvas_c.pack()
canvas_c.config(bg="blue")
Label(canvas_c,text="info").place(x=100,y=250)
ba=Button(root,text="new_window",command=new_window).pack()
bb=Button(root,text="destroy() in canvas",command=canvas_c.destroy).pack()
root.mainloop()
and run run.jpg

Python GUI not updating info after program has launched

This is what I've written (alot of inspiration from online, since im a student and just started learning python). When I open the program, theres a GUI with one button. When I press the button it displays the time as it should. But if i close the popup window, and press it again, the time is the same as it was last time. In short: I have to re-open the program to display current time (since it does not update with current time after it opens).
import Tkinter as tk
import tkMessageBox
import datetime
ctime = datetime.datetime.now() .strftime("%Y-%m-%d %H:%M:%S")
top = tk.Tk()
def showInfo():
tkMessageBox.showinfo( "Today:", str(ctime))
B = tk.Button(top, text ="Click to show current time", command = showInfo)
B.pack()
top.mainloop()
Try this:
import Tkinter as tk
import tkMessageBox
import datetime
top = tk.Tk()
def showInfo():
ctime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
tkMessageBox.showinfo( "Today:", str(ctime))
B = tk.Button(top, text ="Click to show current time", command = showInfo)
B.pack()
top.mainloop()
put ctime inside the function showInfo to update each time when clicked on the button
You can use a method to get the current time every time you click the button:
import Tkinter as tk
import tkMessageBox
import datetime
def getTime():
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
top = tk.Tk()
def showInfo():
tkMessageBox.showinfo( "Today:", getTime())
B = tk.Button(top, text ="Click to show current time", command = showInfo)
B.pack()
top.mainloop()

Showing Mouseposition with python

I want to track my mouse-position and show that in a tiny window.
For that, I created this piece of code:
#! /usr/bin/python
from Tkinter import *
from Xlib import display
def mousepos():
data = display.Display().screen().root.query_pointer()._data
return data["root_x"], data["root_y"]
root = Tk()
strl = "mouse at {0}".format(mousepos())
lab = Label(root,text=strl)
lab.pack()
root.title("Mouseposition")
root.mainloop()
This little script shows the mouse-position on startup but doesn't refresh it on mouse-movement. I don't get behind it (did I say that I'm new to python?).
I think I have to use an event from Xlib that tells my script when the mouse is moving...
How do I refresh my mouse-position?
Use root.after to call update periodically.
Use strl = tk.StringVar() and tk.Label(...,textvariable=strl) to
allow the Label text to change.
Call strl.set() to change the Label text.
A default value for screenroot equal to display.Display().screen().root was added
to mousepos so that most of that long chain of function calls are
not repeated every time mousepos is called. Calling mousepos() without any arguments will continue to work as usual.
import Tkinter as tk
import Xlib.display as display
def mousepos(screenroot=display.Display().screen().root):
pointer = screenroot.query_pointer()
data = pointer._data
return data["root_x"], data["root_y"]
def update():
strl.set("mouse at {0}".format(mousepos()))
root.after(100, update)
root = tk.Tk()
strl = tk.StringVar()
lab = tk.Label(root,textvariable=strl)
lab.pack()
root.after(100, update)
root.title("Mouseposition")
root.mainloop()

Categories