How to Display Progress bar from Windows shell in TKinter? - python-3.x

I am running an "Any file type to PDF Convertor" code using python. When I convert Word files to PDF, it displays a progress bar in the Windows Shell like so:
But I want this progress bar to be displayed inside the Tkinter window.
Is there a way to do this?
Because when I run it as an exe, I cannot let "-w" stay there otherwise the program crashes.
Here's the code:
from tkinter import *
from PIL import Image
from tkinter import filedialog
def buttonclick():
root.filename=filedialog.askopenfilename(initialdir="Pictures", title="Select File", filetypes=(("All Files","*.*"),("PNG Files","*.png"),("JPG Files","*.jpg")))
try:
locus=root.filename.split(".")
dest=str(locus[0]+".pdf")
if str(locus[-1])=="docx":
from docx2pdf import convert
'''
import ttk as t
progressbar = t.Progressbar(orient=HORIZONTAL, length=200, mode='determinate')
progressbar.pack(side="bottom")
'''
convert(root.filename,dest)
#progressbar.start()
notifier=Label(root, text="File converted to PDF successfully!", fg="green", bg="#BFDFFF").pack()
elif str(locus[-1])=="pdf":
notifier=Label(root, text="PDF file Selected! Choose another file type.", fg="black", bg="#BFDFFF").pack()
elif str(locus[-1])=="":
notifier=Label(root, text="Please select a file!", fg="black", bg="#BFDFFF").pack()
else:
imge=Image.open(root.filename)
im1 = imge.convert('RGB')
im1.save(dest)
notifier=Label(root, text="File converted to PDF successfully!", fg="green", bg="#BFDFFF").pack()
except:
notifier=Label(root, text="An unexpected error occured!", fg="red", bg="#BFDFFF").pack()
root=Tk()
root.title("Any File to PDF Convertor")
root.config(bg="#BFDFFF")
root.geometry("300x200")
root.iconbitmap("D:\Coding\MyIcon.ico")
convert=Button(root, text="Select File",font=("Helvetica", 20), bg="#85FF97",command=lambda: buttonclick())
convert.pack(pady=20)
root.mainloop()

Why not try a progress bar widget. Check out this code. I did not bother adapting my solution to your case since you have accepted the answer:
from tkinter import *
from tkinter.ttk import *
import os
root = Tk()
# I set the length and maximum as shown to demonstrate the process in the
# proceeding function. Pay attention to the increment r
progress = Progressbar(root, orient = HORIZONTAL,
length = 200/5, maximum=200/5, mode = 'determinate')
# Function
def my_func():
t=0
r= 1/5
for i in range(200):
print(i) #whatever function interests you
t=t+r
progress['value'] = t
root.update_idletasks()
progress.pack()
# Button
Button(root, text = 'Start', command = bar).pack(pady = 10)
mainloop()

Related

button to take frame screenshot

can someone help me take a screnshot of a specific frame?
been playing with these, but cant seem to specify just the frame
import pyautogui
#im1 = pyautogui.screenshot()
#im1.save('my_screenshot.png')
#im2 = pyautogui.screenshot('my_screenshot2.png')
from tkinter import *
import time
from PIL import ImageTk, Image
import pyautogui as pg
# Create an instance of tkinter frame or window
win = Tk()
# Set the size of the window
win.geometry("700x350")
frm2shoot = Frame(win)
frm2shoot.grid(column=0, row=0)
lbl = Label(frm2shoot, width=16, text="testing testing:", justify=LEFT, anchor="w").grid(row=0, column=0, sticky=W, pady=2)
# Define a function for taking screenshot
def screenshot():
random = int(time.time())
filename = "/Users/ricardosimoes/Desktop/"+ str(random) + ".jpg"
ss = pg.screenshot(filename)
ss.show()
frm2shoot.deiconify()
# Create a Button to take the screenshots
button = Button(win, text="Take Screenshot", font=('Aerial 11 bold'), background="#aa7bb1", foreground="white", command=screenshot)
button.grid(column=5, row=0)
win.mainloop()
Anyone have any idea how to do this??

Tkinter throws exception, but the code still works, why?

I am working on a comic book reader and my code so far seems to be working great, except for a small result that happens when I update my canvas to display a jpg of the page of the comic book.
The Code:
from tkinter import *
from tkinter import filedialog, Tcl
from PIL import ImageTk, Image
from pyunpack import Archive
import shutil
import tempfile
import os
def open_comic():
os.mkdir('tmp/')
text_file = filedialog.askopenfilename(title="Open Comic Book File", filetypes=(("CBR Files", "*.cbr"), ("CBZ Files", "*.cbz"), ))
tempdir = tempfile.mkdtemp(suffix='.tmp', dir='tmp/')
print('Created temp directory', tempdir)
Archive(text_file).extractall(tempdir)
file_list = os.listdir(tempdir)
file_list.sort()
img = ImageTk.PhotoImage(Image.open(tempdir + "/" + file_list[1]))
my_image = comic_canvas.create_image(0, 0, anchor=NW, image=img)
canvas.update()
# Create the Main Window of the Application
mainWindow = Tk()
mainWindow.title("Comic Reader")
mainWindow.geometry("1200x1500")
buttonFrame = LabelFrame(mainWindow)
canvasFrame = LabelFrame(mainWindow, bg="light gray", border=2)
statusFrame = LabelFrame(mainWindow, bg="black", border=2)
comic_canvas = Canvas(canvasFrame, width="1100", height="1400", bg="light gray")
# Create the Menu Bar for the Application
main_menu = Menu(mainWindow)
mainWindow.config(menu=main_menu)
# The File Menu
file_menu = Menu(main_menu, tearoff=False)
main_menu.add_cascade(menu=file_menu, label="File")
file_menu.add_command(label="Open", command=open_comic)
file_menu.add_separator()
file_menu.add_command(label="Quit", command=quit_it)
# The Edit Menu
edit_menu = Menu(main_menu, tearoff=False)
main_menu.add_cascade(menu=edit_menu, label="Edit")
edit_menu.add_command(label="Cut", accelerator="(CTRL+X)")
edit_menu.add_command(label="Copy", accelerator="(CTRL+C)")
edit_menu.add_command(label="Paste", accelerator="(CTRL+V)")
button_back = Button(buttonFrame, text="<=", command=back)
button_exit = Button(buttonFrame, text="Exit", command=quit_it)
button_next = Button(buttonFrame, text="=>", command=lambda: forward(2))
buttonFrame.pack()
canvasFrame.pack()
statusFrame.pack()
button_back.grid(row=1, column=0)
button_exit.grid(row=1, column=1)
button_next.grid(row=1, column=2)
comic_canvas.grid(row=2, column=1)
# Start the Application Here
mainWindow.mainloop() # Creates the GUI for the Application
Now as it is above, it works to update the canvas, and lets you see the image, but throws the error:
> Exception in Tkinter callback Traceback (most recent call last):
> File
> "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py",
> line 1884, in __call__
> return self.func(*args) File "/Users/kb2mob/Python Projects/Comic Reader/comicreader.py", line 28, in open_comic
> canvas.update() NameError: name 'canvas' is not defined
Which, yeah it should because the canvas is named "comic_canvas". But then I do use the correct name for the .update() method, it flashes quickly and then vanishes, and of course doesn't throw an error because it's the correct use.
Does anyone know why that is?
This is in Python 3.9.1 on a latest Mac OS.
Found the issue:
Wasn't keeping the image reference at the end of my function open_comic()
comic_canvas.img = img
dropped that on the end of it and it worked.

Python - run a Pandas script with a Tkinter GUI

I'm trying to set up a GUI with tkinter, I used this post -
Use Tkinter to Open file, run script and export file as a reference and a great tutorial on youtube -
https://www.youtube.com/watch?v=D8-snVfekto&t=2374s.
I want to be able to browse for a file, execute a pandas script that i have (for this example i only wrote something simple just to check if it works) and then save it.
i'm having some issues with the script_python function. I get a name "df" is not defined error.
(I called global df because i had a "local variable 'df' referenced before assignment" error and that what solved it)
It should be a straight forward solution but somehow i can't wrap my head around it.
Thanks a lot!
import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
import pandas as pd
HEIGHT=400
WIDTH=500
def load():
name = askopenfilename(filetypes=[('CSV', '*.csv',), ('Excel', ('*.xls', '*.xslm', '*.xlsx'))])
if name.endswith('.csv'):
df = pd.read_csv(name)
else:
df = pd.read_excel(name)
return df
def script_python():
global df
df = df.drop(columns=['x','y'])
def file_save():
fname = asksaveasfilename(filetypes=(("Excel files", "*.xlsx"),("All files", "*.*")))
df.to_excel(fname)
root= tk.Tk()
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()
background_image = tk.PhotoImage(file='pic.png')
background_label =tk.Label(root,image=background_image)
background_label.place(x=0,y=0, relwidth=1,relheight=1)
frame= tk.Frame(root,bg='#80c1ff', bd=5)
frame.place(relx=0.5, rely=0.1,relwidth=0.5,relheight=0.1, anchor= 'n')
button = tk.Button(frame, text= 'Browse file', font=40, command=load)
button.place(relx=0.5, relwidth=0.5, relheight=1,anchor='n')
lower_frame= tk.Frame(root,bg='#80c1ff',bd=5)
lower_frame.place(relx= 0.5, rely= 0.5, relwidth=0.5, relheight=0.1, anchor='s')
lower_button = tk.Button(lower_frame, text= 'Execute script', font=10,command=script_python)
lower_button.place(relx=0.5,rely=0.8, relwidth=0.5, relheight=1,anchor='s')
save_button=tk.Button(root, text= 'Save', font=40,command=file_save)
save_button.pack()
root.mainloop()
your file_save() function does not declares df as global so it does not "know" the global df.

tkinter can not display the image

I want to put an image(light.gif) in the button of tkinter.
However, the image is not shown and only a small transparent box appears at the specified position.
My Code is
from tkinter import* #To use Tkinter
from tkinter import ttk #To use Tkinter
from tkinter import messagebox #To use Tkinter
import tkinter.font # To use Font
win = Tk()
win.title("Main Control")
win.geometry('450x400+100+300')
win.resizable(0,0)
def a1():
a1 = Toplevel()
a1.title("a1")
a1.geometry('450x350+560+100')
a1.resizable(0,0)
lignt_sensor_image=PhotoImage(file = 'light.gif')
light_sensor_button=Button(a1,width=15,height=8)
light_sensor_button.place=(x=275,y=200)
a1.mainloop()
newa1 = Button(win, text='A1', font=font1, command=a1, height = 5, width = 10)
newa1.place(x=50, y=30)
win.mainloop()
Please help me
You must keep a reference to the image; as it is created in a function, it was destroyed the moment the function exited.
There also were typos in your code that prevented it from running.
The following shows your image in the popup window.
import tkinter as tk
from tkinter import PhotoImage
def spawn_toplever_a1():
global light_sensor_image # <- hold the image in the global variable, so it persists
a1 = tk.Toplevel() # do not name your variables the same as your function
a1.title("a1")
a1.geometry('450x350+560+100')
light_sensor_image = PhotoImage(file='light.gif')
light_sensor_button = tk.Button(a1, image=light_sensor_image, text="my image", compound="center")
light_sensor_button.place(x=275,y=100) # <-- typo - removed '=' sign
# <-- removed call to mainloop
light_sensor_image = None # declare variable to hold the image
win = tk.Tk()
win.title("Main Control")
win.geometry('450x400+100+300')
win.resizable(0,0)
newa1 = tk.Button(win, text='A1', command=spawn_toplever_a1, height = 5, width = 10)
newa1.place(x=50, y=30)
win.mainloop()

Tkinter "Open" Window

I want to replicate the "Open" button (For example on notepad to open a txt file) but I want to have it as a button beside entry in a tkinter window so I could either enter a directory or use button to select a specific folder.
import glob
import os
from tkinter import *
import tkinter.messagebox
for file in os.listdir(r"C:\directory"):
print(file)
root = Tk()
root.resizable(width=FALSE, height=FALSE)
def inital():
pass
#Making Widgets
frameT = Frame(root)
frameT.pack(side=TOP)
frameB = Frame(root)
frameB.pack(side=BOTTOM)
labelstart = Label(frameT, text="Configure")
labelstart.grid()
dirlabel = Label(frameT, text="Directory:")
dirlabel.grid(row=1)
dirinput = Entry(frameT)
dirinput.grid(row=2)
root.mainloop()
How about this :
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog
def askopenfile():
# If you want to browse files.
path_to_file = tkFileDialog.askopenfilename() # for a file
# If you want to browse directories.
path_to_folder = tkFileDialog.askdirectory() # for a directory
print "File: " + path_to_file
print "Folder: " + path_to_folder
root = Tk()
b = Button(root, text="CLICK ME", command=askopenfile)
b.pack()
root.mainloop()
Hopefully this will help you, Yahli.

Resources