tkinter - open file with button and save filename to variable - python

I am trying to solve a problem that seems simple, but I cannot figure out how.
I want to create a simple program checking if a certain symbol exists in a text file:
The program starts;
The user clicks a button (inside the window, not in the menu);
A dialog box appears;
The user chooses a text file;
A message box displays the result;
The program closes.
Pretty straightforward, but I cannot find how to save the filename into a variable and then use it for the process. I read so many tutorials and I could not find a solution. Here is the code:
from tkinter import *
from tkinter import filedialog
def clicked():
global filename
filename = filedialog.askopenfile(filetypes=(("Word files","*.docx"),))
window = Tk()
window.geometry()
window.title("My App")
open_file_label = Label(window, text="Open your docx file here:", font=("Arial", 10), padx=5, pady=5)
open_file_label.grid(column=0, row=0)
open_file_button = Button(window, text="Click me", command=clicked, padx=5, pady=5)
open_file_button.grid(column=1, row=0)
window.mainloop()

filename is already a variable that contains the chosen file's contents. Just print(filename) and you'll get your data printed in console.

Related

Tkinter window closing, but python script stays running

I've tried a variety of things but can't seem to figure this out.
Here's a general overview of my program, which takes an Excel file as an import and outputs a .pdf of charts:
Ask user to enter a file name for the outputted file (using Tkinter textbox input)
Ask user to select the input file (using askopenfilename)
Does a bunch of work with Pandas to analyze data, then plots it with matplotlib and PdfPages
Displays a message with Tkinter that says the file was outputted successfully, along with a "Exit" button, which should end the program, but does not.
Here's #1 (separately, I'm wondering how I could modify this code to accept the "Enter" button instead of having to physically click the button):
root = tk.Tk()
root.title("Enter a file name for the report")
def getOutputFileName():
global outputFileName
outputFileName = textBox.get("1.0",'end-1c')
print(outputFileName)
root.quit()
textBox = Text(root, height=1, width = 25)
textBox.pack()
buttonCommit = Button(root, height=5, width=50, text="After entering a file name, click here.", command=lambda: getOutputFileName())
buttonCommit.pack()
root.mainloop()
root.withdraw()
Here's #2:
filetypes=[("Excel files", ".xlsx .xls")]
file_path = fd.askopenfilename(filetypes=filetypes, title = 'Open the Excel input file')
df = pd.read_excel(file_path) ## Start of Pandas code
#3 shouldn't be relevant as it doesn't use Tkinter whatsoever (plus the .pdf is exporting correctly), so here's #4:
window = tk.Toplevel() ## Here I tried using root = tk.Tk() but learned that Toplevel() needs to be used for windows after the first?
window.Title = "Success!"
window.geometry("250x170")
T = Text(window, height = 5, width = 52)
successText = "Report successfully generated. The .pdf file was saved to the same location from which you ran this program. You may close the program now."
b1 = Button(window, text = "Exit", command = window.destroy) ## This button DOES close the window, but doesn't close the entire program (i.e. my IDE stays running the script until I force stop)
T.pack()
b1.pack()
T.insert(tk.END, successText)
tk.mainloop()
print("End of program.") ## this is for testing - the program never gets here.
Any advice would be amazing. Thank you.

Button.wait_variable usage in Python/Tkinter

There have already been several topics on Python/Tkinter, but I did not find an answer in them for the issue described below.
The two Python scripts below are reduced to the bare essentials to keep it simple. The first one is a simple Tkinter window with a button, and the script needs to wait till the button is clicked:
from tkinter import *
windowItem1 = Tk()
windowItem1.title("Item1")
WaitState = IntVar()
def submit():
WaitState.set(1)
print("submitted")
button = Button(windowItem1, text="Submit", command=submit)
button.grid(column=0, row=1)
print("waiting...")
button.wait_variable(WaitState)
print("done waiting.")
windowItem1.mainloop()
This works fine, and we see the printout “done waiting” when the button is clicked.
The second script adds one level: we first have a menu window, and when clicking the select button of the first presented item, we have a new window opening with the same as above. However, when clicking the submit button, I don’t get the “Done waiting”. I’m stuck on the wait_variable.
from tkinter import *
windowMenu = Tk()
windowMenu.title("Menu")
def SelectItem1():
windowItem1 = Tk()
windowItem1.title("Item1")
WaitState = IntVar()
def submit():
WaitState.set(1)
print("submitted")
button = Button(windowItem1, text="Submit", command=submit)
button.grid(column=0, row=1)
print("waiting...")
button.wait_variable(WaitState)
print("done waiting")
lblItem1 = Label(windowMenu, text="Item 1 : ")
lblItem1.grid(column=0, row=0)
btnItem1 = Button(windowMenu, text="Select", command=SelectItem1)
btnItem1.grid(column=1, row=0)
windowMenu.mainloop()
Can you explain it?
Inside your SelectItem1 function, you do windowItem1 = Tk(). You shouldn't use Tk() to initialize multiple windows in your application, the way to think about Tk() is that it creates a specialized tkinter.Toplevel window that is considered to be the main window of your entire application. Creating multiple windows using Tk() means multiple main windows, and each one would need its own mainloop() invokation, which is... yikes.
Try this instead:
windowItem1 = Toplevel()

How to automatically add a scrollbar to a tkinter window when it gets to big for the screen?

I want to display a list of files being processed from a directory. If the directory has a lot of files the window gets bigger than the screen and cuts off without adding a scroll bar.
I've seen some solutions to add scrollbars to widgets but I didn't seeanything to manage the entire window or how to have it appear just when the content doesn't fit like most other app windows. Is there a command to let the operating system manage when the scrollbar appears?
Here's the code I have so far, at the moment it just displays file names but I want to add what's done to them later.
import tkinter
from pathlib import Path
def start():
progressWindow = tkinter.Toplevel(mainWindow)
tkinter.Label(progressWindow,text="File name").grid(row=0, column=0,sticky="w")
tkinter.Label(progressWindow,text="Analysis results").grid(row=0, column=1, sticky="w")
tkinter.Label(progressWindow, text="File moved and renamed").grid(row=0, column=2, sticky="w")
gridRow = 1
sourcePath = Path(r"C:\Users\Sulley\Downloads")
for file in sourcePath.iterdir():
if not file.is_file():
continue
if not file.suffix == ".pdf":
continue
tkinter.Label(progressWindow,text=file.name).grid(row=gridRow,column=0, sticky="w")
gridRow += 1
tkinter.Button(progressWindow,text="Done", command=progressWindow.destroy).grid(row=gridRow, column=1)
mainWindow = tkinter.Tk()
mainWindow.title("Sort Bill PDFs")
# Go/cancel
tkinter.Button(mainWindow,text="Cancel", command=quit).pack()
tkinter.Button(mainWindow,text="Go!", command=start).pack()
mainWindow.mainloop()

Choosing file by clicking on a button [Python 2.7.6]

I'm trying to create a simple button that allows me to choose files such as text doc/pictures(jpg/png). I tried searching for answers here but didn't had any luck. I'm using Tkinter for my GUI interface.
This are my codes so far.
from Tkinter import *
root = Tk()
root.title("Hashing Tool")
root.geometry("600x300")
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
button = Button(frame, text="Choose File", fg="black")
button.pack( side = BOTTOM)
from tkFileDialog import askopenfilename
filename = askopenfilename()
print(filename)
root.mainloop()
Currently, you ask for a file as soon as the program starts. You have to put that part of the code into a callback function and pass that to the button's command parameter.
def getfile():
filename = askopenfilename()
print(filename)
button = Button(frame, text="Choose File", fg="black", command=getfile)

Show user a message in python

quick question here. Is there a really easy way to show a user a message in like a text box in python? I just need to input a string beforehand so I can show the message after a loop runs. Thanks!
EDIT: Just Windows 8.1 and straight python 2.7
If I'm correct that you want a window to let a user type in some text, then show it back as a message box, then you need two modules, tkMessageBox and Tinker, two standard modules in Python 2.7+.
The following documented code does the above
from Tkinter import *
import tkMessageBox
def getInfo():
#This function gets the entry of the text area and shows it to the user in a message box
tkMessageBox.showinfo("User Input", E1.get())
def quit():
#This function closes the root window
root.destroy()
root = Tk() #specify the root window
label1 = Label( root, text="User Input") #specify the label to show the user what the text area is about
E1 = Entry(root, bd =5) #specify the input text area
submit = Button(root, text ="Submit", command = getInfo) #specify the "submit" button that runs "getInfo" when clicked
quit_button = Button(root, text = 'Quit', command=quit) #specify the quit button that quits the main window when clicked
#Add the items we specified to the window
label1.pack()
E1.pack()
submit.pack(side =BOTTOM)
quit_button.pack(side =BOTTOM)
root.mainloop() #Run the "loop" that shows the windows

Categories