Python GUI not updating info after program has launched - python

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()

Related

How would I continue to run code after importing a Tkinter file?

So I'm trying to use a Tkinter window as an output log. My main program is a command line interface, so if the output from the "side programs" that run fills up the python console, it can ruin the user experience.
I have the Tkinter output log program in a seperate file, which I import into my main file. This is the gyst of the Tkinter file I created:
import time
from datetime import datetime
root = Tk()
root.configure(background='black')
root.geometry('700x460')
console = Listbox(root, width=40000, height=30000, font=('Lucida Console', 14), relief=FLAT, bg='black',
fg='white',
borderwidth=0, highlightbackground='black', selectbackground='black',
selectforeground='white')
console.pack()
def log(what_to_log):
now = datetime.now()
console.insert('[' + now.strftime("%H:%M:%S") + ']: ' + what_to_log)
root.mainloop()
So I import it into my main program like so:
# this is the file with the Tkinter code
import Logs
Logs.log('Test')
The issue is that the main program doesn't continue running after importing Logs, it just stops, and continues to run the mainloop in the Logs file.
So my question is, how could I get both files to continue running, while also being able to update the Tkinter listbox via the log function??
You should not execute root.mainloop() as it will block your console application. Use root.update() at the end of log() to force tkinter to update the list box. Also there is syntax error in console.log(...).
Below is a modified Logs.py:
from tkinter import *
from datetime import datetime
root = Tk()
root.configure(background='black')
root.geometry('700x460')
console = Listbox(root, font=('Lucida Console', 14), relief=FLAT, bg='black', fg='white',
borderwidth=0, highlightbackground='black', selectbackground='black',
selectforeground='white')
console.pack(fill='both', expand=1)
def log(what_to_log):
now = datetime.now()
console.insert('end', '['+now.strftime("%H:%M:%S")+']: '+what_to_log)
console.see('end') # make sure last log is visible
root.update() # force tkinter to update

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 running clock in separate window

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.

python button combination to open a tkinter message box

im new topython 2.7 and want to know if it is possible to open a tkinter messagebox with a button combination on keyboard (Ctrl+alt+'something')
that pops up like an windows error message
import win32api
import time
import math
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
def Message():
tkMessageBox.showinfo("Window", "Text")
for i in range(9000):
x = int(600+math.sin(math.pi*i/100)*500)
y = int(500+math.cos(i)*100)
win32api.SetCursorPos((x,y))
time.sleep(.01)
Yes, you can bind to control and alt characters. Bindings are fairly well documented. Here's one good source of information:
http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm
As an example, to bind to ctrl-alt-x you would do this:
top.bind("<Control-Alt-x>", Message)
You can bind to a sequence of events by specifying the whole sequence. For example, if you wanted to implement a cheat code you could do something like this:
label.bind("<c><h><e><a><t>", Message)
For letters, "a" is the same as "<a>", so you can also do this:
label.bind("cheat", Message)
Here is a complete working example:
import Tkinter as tk
import tkMessageBox
def Message(event=None):
tkMessageBox.showinfo("Window", "Text")
def Cheat(event=None):
tkMessageBox.showinfo("Window", "Cheat Enabled!")
root = tk.Tk()
label = tk.Label(root, text="Press control-alt-m to see the messagebox\ntype 'cheat' to enable cheat.")
label.pack(fill="both", expand=True, padx=10, pady=100)
label.bind("<Control-Alt-x>", Message)
label.bind("<c><h><e><a><t>", Cheat)
label.focus_set()
root.mainloop()
If you want something like: Press button A, then press button B then open a Message box it is possible.
Do something like:
from Tkinter import *
import tkMessageBox
def change():
global switch
switch=True
def new_window():
if switch:
tkMessageBox.showinfo("Random name", "Correct combination")
else:
print "Not the correct order"
root = Tk()
switch = False
root.bind("<A>", change)
root.bind("<B>",new_window)
root.mainloop()
If you want more buttons then use an integer and increase it while using switches for the correct button order.
Note that you can bind key combinations as well with root.bind("<Shift-E>") for example
Edit: Now a and b keyboard button insted of tkinter buttons

Problems using Tkinter askopenfile

I want to launch an "Open File" dialog in Tkinter in Python 2.7.
My code starts with:
from Tkinter import Frame, Tk, BOTH, Text, Menu, END
import tkFileDialog as tkfd
import fileinput
root = Tk()
global strTab
strTab = ""
def openTab(event):
r = tkfd.askopenfilename()
strTab = unicodedata.normalize('NFKD', r).encode('ascii','ignore')
Later in the code I have:
btnLoadTab = Button(root,
text="Load Tab",
width=30,height=5,
bg="white",fg="black")
btnLoadTab.bind("<Button-1>", openTab)
btnLoadTab.pack()
root.mainloop()
When I press the button an "Open File" dialog is shown, but when I select a file it closes and the button remains "clicked".
If I later call to strTab outside of openTab, it remains equal to "".
You can find workable example here: http://www.python-course.eu/tkinter_dialogs.php

Categories