tkinter:2 windows pop up at the same time - python

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

Related

Tkinter getting file path returned to main function to use and pass on to other functions

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 make a exe similar to windows file explorer with python using os.path and tkinter

from PIL import Image
from tkinter import filedialog as fd
import os
import ctypes
import tkinter
class ImageList:
path = ""
dir = ""
top = tkinter.Tk()
canvas = tkinter.Canvas()
canvas.pack()
def __init__(self):
self.path = os.path.expanduser('~/')
def findImage(self):
image = Image.open(self.dir, "rb")
image.show()
def fileExplorer(self, path):
self.canvas.destroy()
self.canvas = tkinter.Canvas()
self.canvas.pack()
obj = os.scandir(path)
for entry in obj:
if entry.is_dir():
#self.path = os.path.abspath(self.path)
b = tkinter.Button(self.canvas, text=entry.name, command=lambda: self.fileExplorer(os.path.abspath(entry).replace('//', '\\')))
b.pack()
elif entry.is_file():
b = tkinter.Button(self.canvas, text=entry.name, command=lambda: print(entry.name))
b.pack()
else:
obj.close()
self.top.mainloop()
As shown in the code above, I am trying to make exe that shows the subdirs and files after C:\Users using buttons in tkinter and repeating it by using recursion.
The first error is that in "os.path.abspath(entry).replace('//', '\')" shows path in a format of "C://Users" and I intended to change that to "C:\Users" using the replace method. However, using "\" doesn't replace "//" and still shows as the original format.
The second error is that after running the code, when I press any button it acts as if I pressed the last button in the tkinter window, meaning that it recursively called the last subdir or the file below "C:\Users".
I'm just getting used to python and this is my first time using stackoverflow. I'm sorry if I did not abide by any of the rules in stackoverflow. Thanks for anyone helping.

how to save the name of the app chosen in tkinter filedialog

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

How I used tkinter button to Import files

I would like to run a python program and when clicking a button in a (tkinter) window become import files form any direction and store it to another direction and in database .
import tkinter as tk
from tkinter import filedialog
def UploadAction(event=None):
filename = filedialog.askopenfilenames()
print('Selected:', filename)
root = tk.Tk()
button = tk.Button(root, text='import files', command=UploadAction)
button.grid(row=1,column=1,padx=10,pady=10)
root.mainloop()

Python - tkinter and glob.glob working togheter

Im new to tkinter and trying to open the explorer (on windows) so that i can chose what folder i want to use in my program. I found a template for tkinter and altered it to work with my function and how i need the filepath to be. Before i tried using tkinter to "select my folder", i had manually writen the directory in the glob.glob function like this glob.glob(r'C:\Users\Desktop\Spyder\*.log') (and it worked). So my new ide was to replace the pathname input from r'C:\Users\Desktop\Spyder\*.log' to a variabel that stored the same pathname but now it used tkinters askdirectory() to finde the directory inteed.
import glob
import os
from itertools import zip_longest
import tkinter as tk
from tkinter import filedialog
#-------------Connect to Access2013------------------
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.create_widgets()
def create_widgets(self):
self.select_folder = tk.Button(self)
self.select_folder["text"] = "Open WindowsExplorer"
self.select_folder["command"] = self.ask_directory_to_folder
self.select_folder.pack(side="top")
self.quit = tk.Button(self, text="QUIT", fg="red",
command=root.destroy)
self.quit.pack(side="bottom")
def ask_directory_to_folder(self):
clerdatabase() # a funktion that resets the autonumber and deleats all data from every table
print("Open!")
filepath = filedialog.askdirectory()
log_filepath = "r'"+ str(filepath +"/*.log'")
right_log_filepath = log_filepath.replace('/','\ ').replace(' ','')
find_filenames(right_log_filepath)
root = tk.Tk()
app = Application(master=root)
app.mainloop()
#--------------Scan selected folder for .log files and starts to scan files---------
def find_filenames(right_log_filepath): #finds every file in the chosen filepath
print(right_log_filepath) # r'C:\Users\Desktop\Spyder\*.log'
print("ok")
filenames = [] # list for all the found filenames
for filepath_search in glob.glob(str(right_log_filepath), recursive=True): #A for loop that opens every .log file in the chosen directory folder
print('run')
My problem ist that i don´t get the for loop filepath_search to work (it prints "ok"). But the word run inside the for loop dose not print, i guess it´s because it gets stuck somewhere before that? Someone who has more experience with tkinter that can help me? Thanks
I guess issue caused by what is passed to glob.glob since it doesn't find anything. It seems that it is mostly related to the fact that you add ' characters at the beggining and end of your right_log_filepath.
In ask_directory_to_folder function replace:
log_filepath = "r'"+ str(filepath +"/*.log'")
right_log_filepath = log_filepath.replace('/','\ ').replace(' ','')
find_filenames(right_log_filepath)
With:
from os import path # should be at the top of your file
log_filepath = path.join(filepath, "*.log")
find_filenames(log_filepath)

Categories

Resources