Python - run a Pandas script with a Tkinter GUI - python-3.x

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.

Related

unable to apply a ttk theme to .toplevel()

I'm trying to rcreate a slasph screen which doubles as an about screen on a menu bar in tkinter and python 3.
so far I've read I should be using a Toplevel() method on the second splash_root but It justs send me the error that, name 'Toplevel' is not defined.
Have I missed something basic here or just misunderstood how Toplevel() works?
import tkinter as tk
import tkinter.ttk as ttk
from PIL import ImageTk, Image
from ttkthemes import ThemedTk
def splash_screen():
splash_root = Toplevel(root)
splash_root.geometry("500x400")
img_title = ImageTk.PhotoImage(Image.open("art/icons/random.png"))
lbl_img_title = ttk.Label(splash_root,image=img_title)
lbl_img_title.pack(side="top",pady=20)
splash_label_by = ttk.Label(splash_root, text="name")
splash_button = ttk.Button(splash_root, text="close", command=lambda: splash_root.destroy())
splash_label_by.pack(pady=20, padx=20)
splash_button.pack(ipadx=10, ipady=10)
splash_screen()
root = ThemedTk(themebg=True)
root.set_theme('black')
root.title("splash")
root.geometry("500x500")
root.mainloop()
The answer to your question:
#Toplevel(root) is not defined
tk.Toplevel(root) #will solve your Toplevel problem.
If you call
splash_screen()
before declaring root, root will be not defined and your code still wont work.

How to Display Progress bar from Windows shell in TKinter?

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

strange behavior of tkinter with pil image [duplicate]

This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 2 years ago.
I simply want to show an image in a label widget. I managed the task by the following code:
import tkinter as tk
from PIL import Image,ImageTk
import requests
root=tk.Tk()
url="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/500px-SNice.svg.png"
imageurl=requests.get(url, stream=True)
image=Image.open(imageurl.raw)
img = ImageTk.PhotoImage(image.resize(size=(500,500)))
origPictureBox = tk.Label(root, image=img, anchor=tk.NW, height=500, width=500)
origPictureBox.config(image=img)
origPictureBox.pack(side=tk.TOP)
root.mainloop()
However, when I put the main tasks into a function, the picture is not displayed:
import tkinter as tk
from PIL import Image,ImageTk
import requests
def initUI(root):
url="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/500px-SNice.svg.png"
imageurl=requests.get(url, stream=True)
image=Image.open(imageurl.raw)
img = ImageTk.PhotoImage(image.resize(size=(500,500)))
origPictureBox = tk.Label(root, image=img, anchor=tk.NW, height=500, width=500)
origPictureBox.config(image=img)
origPictureBox.pack(side=tk.TOP)
root=tk.Tk()
initUI(root)
root.mainloop()
Can somebody explain this behavior? If other items are to be displayed (buttons, etc.), they are visible, it's just the image that hides.
The same happens if I use a class instead of the function initUI.
It's my first question in stackOverflow and I am sorry, if the answer is obvious.
You need to keep reference to the image, or its get garbage collected
So add:
l = tk.Label(root)
l.image = img
Full code
import tkinter as tk
from PIL import Image,ImageTk
import requests
def initUI(root):
url="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/500px-SNice.svg.png"
imageurl=requests.get(url, stream=True)
image=Image.open(imageurl.raw)
img = ImageTk.PhotoImage(image.resize(size=(500,500)))
l = tk.Label(root)
l.image = img
origPictureBox = tk.Label(root, image=img, anchor=tk.NW, height=500, width=500)
origPictureBox.config(image=img)
origPictureBox.pack(side=tk.TOP)
root=tk.Tk()
initUI(root)
root.mainloop()

python tkinter update content of a label when a file is opened

I'm currently programming a GUI using tkinter and Python 3.
My problem here is i made a Label with which i want to display the path of a file i opened via the askopenfilename() method and this path is not "generated" when i start the program, obviously, so the Label is empty which makes sense but i don't know how to fix it.
I'm gonna put the needed code below (I'm going to cut unnecessary code for this question):
import tkinter as tk
class Graphicaluserinterface(tk.Frame):
def __init__(self,master=None):
super().__init__(master)
self.grid()
self.fileopenname=tk.StringVar()
self.menubar = tk.Menu(self)
self.create_widgets()
def create_widgets(self):
self.inputpathdisplay = tk.Label(self,textvariable=self.fileopenname,bg="white",width=30)
self.inputpathdisplay.grid(row=1,column=8,columnspan=3,sticky = "W")
def fileopening(self):
from tkinter.filedialog import askopenfilename
self.fileopenname = askopenfilename(filetypes = [("binary files","*.bin*"),("all files","*.*")])
root = tk.Tk()
app = Graphicaluserinterface(master=root)
root.config(menu=app.menubar)
app.mainloop()
I read about using update_idletasks(). If this is correct in my case how would i go about implementing it here?
Right now you are doing self.fileopenname = askopenfilename() and this will redefine self.fileopenname as a string instead of a StringVar(). To correct this you need to set the value of StringVar with set().
That said you should also define all your imports at the top of your code instead of in your function.
import tkinter as tk
from tkinter.filedialog import askopenfilename
class Graphicaluserinterface(tk.Frame):
def __init__(self,master=None):
super().__init__(master)
self.grid()
self.fileopenname=tk.StringVar()
self.menubar = tk.Menu(self)
self.inputpathdisplay = tk.Label(self, textvariable=self.fileopenname, bg="white")
self.inputpathdisplay.grid(row=1,column=8,columnspan=3,sticky = "W")
self.fileopening()
def fileopening(self):
self.fileopenname.set(askopenfilename(filetypes = [("binary files","*.bin*"),("all files","*.*")]))
root = tk.Tk()
app = Graphicaluserinterface(master=root)
root.config(menu=app.menubar)
app.mainloop()

Trying to make a program that you push a button, choose a file, and the program then prints a certain value from that file

I'm very new to coding and I tried a bunch of different things but none of them are working for me.
Here is my code. With this code everything is working correctly so far, but i'm unsure of how to implement the read function into my code. My main problem is that in everyone's read examples they use the exact filename, whereas I need to use raw input.
Edit: I was able to solve this on my own, by using open(filename, "r") it lets you pick which file to read. Instead of having "6543.txt" which would only open that specific file.
from tkinter import Tk
from tkinter import *
from tkinter.filedialog import askopenfilename
root = Tk()
root.title("Amazon Error Handler")
root.geometry("300x150")
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
def getfile():
filename = askopenfilename()
print(filename)
getfile = open(filename,"r")
print(getfile.read(1))
print(getfile.read())
button = Button(frame, text="Choose File", fg="black", command=getfile)
button.pack( side = BOTTOM)
root.mainloop()
This is the code I used to solve my own problem. This program is just a button that reads a chosen file and prints it's contents.
from tkinter import Tk
from tkinter import *
from tkinter.filedialog import askopenfilename
root = Tk()
root.title("Amazon Error Handler")
root.geometry("300x150")
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
def getfile():
filename = askopenfilename()
print(filename)
getfile = open(filename,"r")
print(getfile.read(1))
print(getfile.read())
button = Button(frame, text="Choose File", fg="black", command=getfile)
button.pack( side = BOTTOM)
root.mainloop()

Resources