Tkinter "Open" Window - python-3.x

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.

Related

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

Open a file with a button then storing the path in Python3

As the title states, I want to open a file with a browse button then store the file path for later use. I have no issue browsing the file, I just can't get the path to store into a variable. Many thanks.
from tkinter import *
from tkinter import filedialog
import openpyxl
from termcolor import cprint
# initializing tk
root = Tk()
root.title("Tools")
root.geometry("600x300")
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack(side = BOTTOM )
def getFile():
# open dialog box to select file
root.filename = filedialog.askopenfilename(initialdir="/", title="Select file")
#create button
browsebutton = Button(frame, text="Browse", command=getFile)
browsebutton.pack(side = BOTTOM)
#store the open file path into a variable
path = root.filename
You can use global(you should avoid global if possible) or use a class
def getfile():
path.set(filedialog.askopenfilename(initialdir="/", title="Select file")
def do_other_work_with_path():
#your Code here
print(path.get())
path = StringVar()
#using global
def getfile():
global path
path = filedialog.askopenfilename(initialdir="/", title="Select file")
# or using a class for your whole gui
from tkinter import *
from tkinter import filedialog
root = Tk()
class GUI:
def __init__(self, parent):
self.parent=parent
self.button=Button(self.parent, text='Browse', command=self.getfile)
self.button.pack()
def getfile(self):
self.path=filedialog.askopenfilename(initialdir="/", title="Select file")
gui=GUI(root)
#you can also call gui.path with a class
root.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()

Using Tkinter and suprocess.call

I would like to use tkinter to open a window that will allow a user to select two separate files that will be manipulated several times within my script. I am having trouble finding a way to set the file that will be selected using the button in my tkinter window as a variable so that it can be used within subprocess.call. I have found invoke() but it doesn't seem to have any affect. Any ideas on what I might do would be greatly appreciated.
import os
import sys
import gdal
from gdalconst import *
import numpy as np
import math
import subprocess
from subprocess import call
import math
import datetime
import shutil
import tkinter
from tkinter import *
from tkinter import filedialog
newpath = os.path.expanduser('~\\Desktop\\Components\\Float32')
if not os.path.exists(newpath):
os.makedirs(newpath)
newpath_2 = os.path.expanduser('~\\Desktop\\Components\\Zeros')
if not os.path.exists(newpath_2):
os.makedirs(newpath_2)
newpath_3 = os.path.expanduser('~\\Desktop\\Components\\db_Files')
if not os.path.exists(newpath_3):
os.makedirs(newpath_3)
if __name__== '__main__':
# Set all of the necessary constants so that the script can create and save the pertinent files
# on the users desktop
#tk1 = Tk()
#tk2 = Tk()
#callTK = 'src_dataset =' + tk1
#callTK_2 = 'srcVH =' + tk2
gdalTranslate = 'C:\Program Files (x86)\GDAL\gdal_translate.exe'
tk1.fileName = filedialog.askopenfilename(text="Open HV File")
tk2.fileName = filedialog.askopenfilename(text="Open VH File")
dst_dataset = os.path.expanduser('~\\Desktop\\Components\\Float32\\newHV32.img')
dstVH = os.path.expanduser('~\\Desktop\\Components\\Float32\\newVH32.img')
sttime = datetime.datetime.now().strftime('(Time_Run = %Y-%d-%m_%H:%M:%S)')
wheel_install_1 = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\wheel_install.py')
wheel_install_2 = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\wheel_install2.py')
ridofz = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\ridofZsv2.py')
to_dB = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\to_dBv2.py')
db_HV = os.path.expanduser('~\\Desktop\\Components\\dB_Files\\newHVdB.img')
db_VH = os.path.expanduser('~\\Desktop\\Components\\dB_Files\\newVHdB.img')
cmd = "-ot float32 -of HFA" # hopefully this works
# Install necessary packages, which are GDAL and Numpy
# try:
#os.system(wheel_install_1)
#print ("GDAL intalled")
#os.system(wheel_install_2)
#print ("Numpy installed")
#except:
#print ("The packages are't installing properly")
#sys.exit()
# Create three new folders which will house the files that will be created
# along each sequential step of the script
#newpath = os.path.expanduser('~\\Desktop\\Components\\Float32')
#if not os.path.exists(newpath):
#os.makedirs(newpath)
#newpath_2 = os.path.expanduser('~\\Desktop\\Components\\Zeros')
#if not os.path.exists(newpath_2):
#os.makedirs(newpath_2)
#newpath_3 = os.path.expanduser('~\\Desktop\\Components\\db_Files')
#if not os.path.exists(newpath_3):
#os.makedirs(newpath_3)
root = Tk()
#root.fileName = filedialog.askopenfilename()
root.title("Utilis Sigma Test")
root.iconbitmap(r"C:\Users\jack.UTILIS\Desktop\images\sigma.ico")
root.configure(background="#179EBB")
topFrame = Frame(root)
topFrame.pack()
photo = PhotoImage(file="C:\\Users\\jack.UTILIS\\Desktop\\images\\Utilis_Branding2015_FINAL_Small.gif")
label = Label(root, image=photo)
label.pack(side=RIGHT)
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
button1 = Button(root, text="Open HV File", fg="black", command=filedialog.askopenfilename)
button2 = Button(root, text="Open VH FIle", fg="black", command=filedialog.askopenfilename)
button1.pack(side=LEFT)
button2.pack(side=RIGHT)
hvfullCmd = ' '.join([gdalTranslate, cmd, tk1.fileName,dst_dataset])
subprocess.call(hvfullCmd)
vhfullCmd = ' '.join([gdalTranslate,cmd, tk2.fileName,dstVH])
subprocess.call(vhfullCmd)
root.mainloop()
You have to create own function which get filename from askopenfilename and does something with this file. Then you can assign this file to button using command=
import tkinter as tk
from tkinter import filedialog
# --- functions ---
def on_click():
filename = filedialog.askopenfilename()
if filename:
print("Filename:", filename)
else:
print("Filename: not selected")
# --- main ---
root = tk.Tk()
btn = tk.Button(root, text='Click Me', command=on_click)
btn.pack()
root.mainloop()

Python 3 Tkinter - Messagebox with a toplevel as master?

I've found that when a toplevel widget calls a messagebox dialog (like "showinfo"), the root window is showed up, over the toplevel. Is there a way to set the Toplevel window as the master of the messagebox dialog ?
Here is a script to reproduce this :
# -*- coding:utf-8 -*-
# PYTHON 3 ONLY
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title('ROOT WINDOW')
Label(root, text = 'Place the toplevel window over the root window\nThen, push the button and you will see that the root window is again over the toplevel').grid()
topWindow = Toplevel(root)
topWindow.title('TOPLEVEL WINDOW')
Label(topWindow, text = 'This button will open a messagebox but will\ndo a "focus_force()" thing on the root window').grid()
Button(topWindow, text = '[Push me !]', command = lambda: messagebox.showinfo('foo', 'bar!')).grid()
# --
root.mainloop()
You can set the parent argument to topWindow for the showInfo command:
Button(..., command=lambda: messagebox.showInfo(parent=topWindow, ...))
See also:
http://effbot.org/tkinterbook/tkinter-standard-dialogs.htm
This may address more current versions.
#TEST AREA forcommands/methods/options/attributes
#standard set up header code 2
from tkinter import *
from tkinter import messagebox
root = Tk()
root.attributes('-fullscreen', True)
root.configure(background='white')
scrW = root.winfo_screenwidth()
scrH = root.winfo_screenheight()
workwindow = str(1024) + "x" + str(768)+ "+" +str(int((scrW-1024)/2)) + "+" +str(int((scrH-768)/2))
top1 = Toplevel(root, bg="light blue")
top1.geometry(workwindow)
top1.title("Top 1 - Workwindow")
top1.attributes("-topmost", 1) # make sure top1 is on top to start
root.update() # but don't leave it locked in place
top1.attributes("-topmost", 0) # in case you use lower or lift
#exit button - note: uses grid
b3=Button(root, text="Egress", command=root.destroy)
b3.grid(row=0,column=0,ipadx=10, ipady=10, pady=5, padx=5, sticky = W+N)
#____________________________
root.withdraw()
mb1=messagebox.askquestion(top1, "Pay attention: \nThis is the message?")
messagebox.showinfo("Say Hello", "Hello World")
root.deiconify()
top1.lift(aboveThis=None)
#____________________________
root.mainloop()
Button(..., command=lambda: messagebox.showinfo("The Title", "A piece of text", parent=topWindow))
This will definitely work. The syntax of the messagebox is
messagebox.Function_Name(title, message [, options])
setting the parent argument is one of the options
add topWindow.attributes("-topmost", 1)
after defining the Toplevel, and this should fix the problem

Resources