I want to create a progress bar (GUI) in python. I am not sure how to do this in graphical version
I want it to print status in the output box too.
I am using progressbar2 right now
So here is my code:
import time
import progressbar
for i in progressbar.progressbar(range(100)):
time.sleep(0.02)
Here is a small example for you to add progress bar in gui with status
from tkinter import *
from tkinter.ttk import *
import time
root=Tk()
root.title("hi")
root.geometry("600x400")
a=IntVar()
prog=Progressbar(root,orient=HORIZONTAL,length= 300,mode = 'determinate' )
def step():
for x in range(5):
prog['value']+=20
a.set(prog['value'])
root.update_idletasks()
time.sleep(1)
prog.pack(pady=20)
butn=Button(root,text='Progress',command=step).pack(pady=20)
lb=Entry(root,textvar=a).pack(pady=20)
root.mainloop()
It think it may help you
Related
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.
I am new to tkinter
import datetime as dt
from tkinter import *
from tkinter import messagebox
dt1 = dt.datetime.now().strftime("%Y""%m""%d")
time1 = dt.datetime.now().strftime('%H:%M:%S')
msg1= dt1+" "+time1+ " Test Message XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
master = Tk()
top = Tk()
top.geometry("100x100")
messagebox.showinfo("information", msg1)
top.mainloop()
I have basically 3 issues in this basic code
It is creating additional blank windows along with my message which is not required. How to avoid this ?
I want to display my message into single line how can i do this ?
How to change font and color of this message ?
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
I'm very new Python coding and I'm having trouble linking my tkinter files, currently have 2 files 1 is the welcomescreen.py where user selects the form they wish to fill out, now I want user to go to the form they have selected do the activity and comebck to welcome, like press the quit button.
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
class Feedback:
def __init__(self, master):
#CODING
#at the end
def main():
root = Tk()
feedback = Feedback(root)
root.mainloop()
if __name__ == "__main__":main()
and second file is something like this, actually i coded it pretty much in the same manner
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
class Proj_pres:
"""Defininf clickable labels in frame"""
# CODES
# CODES
# at the end
def main():
root = Tk()
proj_pres = Proj_pres(root)
root.mainloop()
if __name__ == '__main__':main()
I tried the exec command but it didn't help.
Seems like all you need to do is import one of the script files you have in by the other one. Let's say you have the script file my_module1.py which has the widget class MyWidget1 and my_module2.py that has MyWidget2. Also the main part of your body should look like the following:
import my_module2
import tkinter as tk
...
if __name__ == '__main__':
root = tk.Tk()
welcome = MyWidget1(...)
welcome.quit_button['command'] = welcome.destroy
form = my_module2.MyWidget2(...)
root.mainloop()
Here is a minimum working example of my code.
I am trying to plot a live graph using matplotlib by taking some inputs from the user via gui. For building the gui, I used the library easygui
However, there is one problem:
the graph stops building while taking an update from the user and I wish it to continue. Is there something that I'm missing here.
#!/usr/bin/env python
from easygui import *
from matplotlib.pylab import *
import numpy
import random
n = 0
fig=plt.figure()
x=list()
y=list()
plt.title("live-plot generation")
plt.xlabel('Time(s)')
plt.ylabel('Power(mw)')
plt.ion()
plt.show()
calculated=[random.random() for a in range(40)]
recorded=[random.random() for a in range(40)]
possible=[random.random() for a in range(5)]
plt.axis([0,40,0,10000])
for a in range(0, len(recorded)):
temp_y= recorded[a]
x.append(a)
y.append(temp_y)
plt.scatter(a,temp_y)
plt.draw()
msg = "Change"
title = "knob"
choices = possible
if a>9:
b = (a/10) - numpy.fix(a/10)
if b==0:
choice = choicebox(msg, title, choices)
print "change:", choice
here is the download link for easygui
sudo python setup.py install
based on your version of linux or OS. use the following link
Thanks to J.F. Sebastian
import easygui
from Tkinter import Tk
from contextlib import contextmanager
#contextmanager
def tk(timeout=5):
root = Tk() # default root
root.withdraw() # remove from the screen
# destroy all widgets in `timeout` seconds
func_id = root.after(int(1000*timeout), root.quit)
try:
yield root
finally: # cleanup
root.after_cancel(func_id) # cancel callback
root.destroy()
with tk(timeout=1.5):
easygui.msgbox('message') # it blocks for at most `timeout` seconds