from tkinter import *
from tkinter import filedialog
def openFile():
global pathFile
file_path = filedialog.askopenfilename()
path.set(file_path)
pathFile = path.get()
#file_name = ' for example google chrome'
root = Tk()
path = StringVar()
button = Button(text="Choose a program", command=openFile)
button.pack()
root.mainloop()
For example lets say the user chooses to pick chrome.exe, I want the name Google Chrome to be saved in the file_name variable. How can I do that.
Edit: I dont wan't to use the os.path.basename method,the name should be whatever is typed here
Screenshot 1
Screenshot 2
Related
This is my current code.
from tkinter import *
from tkinter import ttk, filedialog
from tkinter.filedialog import askopenfile
import os
def main():
path = open_file()
print(path)
# Create an instance of tkinter frame
win = Tk()
# Set the geometry of tkinter frame
win.geometry("700x350")
def open_file():
file = filedialog.askopenfile(mode='r', filetypes=[('PDF', '*.pdf')])
if file:
filepath = os.path.abspath(file.name)
quit()
print(filepath)
def quit():
win.destroy()
# Add a Label widget
label = Label(win, text="Click the Button to browse the Files", font=('Georgia 13'))
label.pack(pady=10)
# Create a Button
ttk.Button(win, text="Browse", command=open_file).pack(pady=20)
win.mainloop()
if __name__ == '__main__':
main()
I want to create a simple GUI to select a file and then use its path in other functions later on. In the current code the filepath prints out fine after the window closes in the open_file function, but it only works if the print statement is in the function. If I remove it from there and want to print it out(just to test) or use it further to pass it to other functions from main it doesn't seem to work. There is no error but it doesn't print anything either. Any idea?
The problem appears to be is wanting to return a value from a function called with a button. This is apparently not possible. The easiest solution I've found (without changing too much of your code structure) is to use a global variable for filepath. Now you can use it pretty much anywhere you want.
Also, I've removed path = open_file() from your main() function as it is redundant. The function is now called only when the button is pressed and not at every start of the program.
from tkinter import *
from tkinter import ttk, filedialog
from tkinter.filedialog import askopenfile
import os
def main():
print(filepath)
# Create an instance of tkinter frame
win = Tk()
# Set the geometry of tkinter frame
win.geometry("700x350")
def open_file():
file = filedialog.askopenfile(mode='r', filetypes=[('PDF', '*.pdf')])
if file:
global filepath
filepath = os.path.abspath(file.name)
quit()
def quit():
win.destroy()
# Add a Label widget
label = Label(win, text="Click the Button to browse the Files", font=('Georgia 13')) label.pack(pady=10)
# Create a Button
ttk.Button(win, text="Browse", command=open_file).pack(pady=20)
win.mainloop()
if __name__ == '__main__':
main()
I am trying to develop a GUI with tkinter. I have created a function (as a button) to browse for a directory folder ('input folder'). I have a routine linked to another button ('execute') that needs the path from 'input folder'.
I am getting errors when I try to pass the path from 'input folder' into os.chdir inside 'execute'. Example is as follows:
import sys
import os
from tkinter import filedialog
from tkinter import *
window = Tk()
def Input():
filename = filedialog.askdirectory()
global filename
def Extraction():
in_loc = filename
os.chdir(in_loc)
btn = Button(window, text="Extract", bg="black", fg="white", command=Extraction)
btn.pack()
btn2 = Button(text="Input", command=Input).pack()
window.mainloop()
Can anyone reproduce this and tell me what I am doing wrong here?
Thanks :)
Try this:
import sys
import os
from tkinter import filedialog
from tkinter import *
filename = ''
def input_function():
global filename
filename = filedialog.askdirectory()
def extraction():
global filename
in_loc = filename
os.chdir(in_loc)
window = Tk()
btn = Button(window, text="Extract", bg="black", fg="white", command=extraction)
btn.pack()
btn2 = Button(text="Input", command=input_function).pack()
window.mainloop()
As a beginner, I am not familiar with tkinter and I don't know how to improve the following codes which are supposed to function like this:
After running the renamer_v.py file, a window will pop up. It displays a short description at the top and beneath it there is an orange colored buttion 'Click Me'. Click the button and then pop up the second window to select a folder. All titles of files in the folder except the hidden ones and subfolders will be given a serialized prefix.
The problem is that the main window and the second widnow pop up at the same time. Howver, the latter is designed to appear after users clicked the button.
Here is my souce code.
renamer_V1.py:
import win32file
import win32con
import tkinter as tk
from tkinter import Button
from clicked import Clicked
root=tk.Tk()
root.geometry("550x200")
label=tk.Label(root,font=("Arial Bold",15),
text='Please select a directory to rename files in the folder:')
label.pack()
c=Clicked()
btn=Button(root,font=("Arial",15),bg='orange',text="Click Me",command=c.clicked)
btn.pack()
c.clicked()
file_lists=os.listdir(c.file_path)
n=0
for file in file_lists.copy():
oldname=c.file_path+os.sep+file
file_flag=win32file.GetFileAttributesW(oldname)
is_hiden=file_flag & win32con.FILE_ATTRIBUTE_HIDDEN
if os.path.isdir(oldname) or is_hiden:
continue
else:
oldname=c.file_path+os.sep+file
newname=c.file_path+os.sep+'('+str(n+1)+')'+file
os.rename(oldname,newname)
n+=1
label=tk.Label(root,text=str(n)+' file(s) renamed.')
label.pack()
root.mainloop()
clicked.py:
from tkinter import filedialog
class Clicked:
file_path=None
def __init__(self):
print()
def clicked(self):
self.file_path=filedialog.askdirectory(title='ReNamer')
The application is completed and now it is working perfectly under MacOS as desired. Here is the code:
import os
from tkinter import filedialog
import tkinter as tk
from tkinter import Button
root=tk.Tk()
class ReName():
def __init__(self):
self.n = 0
self.label1=tk.Label(root)
def rename(self):
file_path = filedialog.askdirectory(title='ReNamer')
self.file_lists = os.listdir(file_path)
for self.file in self.file_lists.copy():
self.oldname = file_path + os.sep + self.file
if os.path.isdir(self.oldname) or self.file.startswith('.'):
continue
else:
self.newname = file_path + os.sep + '(' + str(self.n + 1) + ')' + self.file
os.rename(self.oldname, self.newname)
self.n+=1
self.label1.config(text='{} file(s) renamed'.format(self.n))
self.label1.pack()
btn.config(state='disabled')
ins=ReName()
root.geometry("550x200")
label=tk.Label(root,font=("Arial Bold",15),
text='Please select a directory to rename files in the folder:')
label.pack()
btn=Button(root,font=("Arial",15),bg='orange',text="Click Me",command=ins.rename)
btn.pack()
root.mainloop()
I am using Tkinter in Python to get user input (Tkinter.Entry) for a folder-path. When the user clicks a button on the GUI, this path is then accepted (get.Entry) and a list of files in that path is created (os.listdir)
I want a drop-down menu OptionMenu to display this list.
My current code does not display the list of files even when the filelist variable is non-empty. Why would this be happening?
After the code has completely run, I checked filelist and found that it is not empty.
Why does the OptionMenu see it as empty then?
Following is my code:
import os
import tkinter as tk
from tkinter import ttk
from IPython.core.debugger import set_trace
filepath = ""
filename = ""
filelist = [""]
root = tk.Tk()
def click():
global filepath, filename, filelist
filepath = e.get()
filelist = os.listdir(filepath)
myLabel = tk.Label(root,text = filelist).pack()
path = tk.StringVar()
e = tk.Entry(root,textvariable = path)
e.pack()
myButton = tk.Button(root, text = "click", command = click).pack()
optionVar = tk.StringVar()
op = tk.OptionMenu(root,optionVar,*filelist)
op.pack()
root.mainloop()
Pic1 shows the contents of my folder.
enter image description here
I figured out that the curly brackets seen around some items in the filelist array are because of the spaces in the filenames.
Pic2 shows the output of the script. Print(filelist) by itself shows empty filelist.
When the 'click' button is pressed, the Label prints the filelist with three items.
But the OptionMenu does not see this updated filelist.
enter image description here
I want to use extensions list example : [".txt",".html",".css"] for save as option in file dialog popup window. when I use this method
file_opt = options = {}
options['defaultextension'] = '.txt',I can able to write any file with .txt as default extension without choose in save as option but I want to choose extensions for save as in file dialog popup window from using my extensions list.
I'm using Python 3.5 based Anaconda IDE
If you look at the documentation here you can see that you can pass in the filetypes keyword which specifies a list of tuples that have the name, and file extension respectively for the different types of filetypes you want to be able to save as.. So you can do something along the lines of:
import tkinter as tk
from tkinter import filedialog as fd
def save_file():
filename = fd.asksaveasfilename(defaultextension='.txt',
filetypes= [('Text','.txt'), ('HTML', '.html'), ('CSS', '.css')])
if filename:
print("User saved the filename with extension:", filename.split(".")[-1])
root = tk.Tk()
button = tk.Button(root, text='Save File', command=save_file)
button.pack()
root.mainloop()
Or if you really want to use a dictionary for this:
import tkinter as tk
from tkinter import filedialog as fd
SAVE_OPTS = {'defaultextension':'.txt',
'filetypes': [('Text','.txt'), ('HTML', '.html'), ('CSS', '.css')]}
def save_file():
filename = fd.asksaveasfilename(**SAVE_OPTS)
if filename:
print("User saved the filename with extension:", filename.split(".")[-1])
root = tk.Tk()
button = tk.Button(root, text='Save File', command=save_file)
button.pack()
root.mainloop()
SaveFileDialog sd = new SaveFileDialog();
sd.Filter = "Text File (*.txt)|*.txt|PNG File (*.txt)|*.png"|...;
if(sd.ShowDialog() == DialogResult.OK) {
richTextBox1.SaveFile(sd.FileName, RichTextBoxStreamType.PlainText);
}