changing extensions of all images in a folder with tkinter - python

I want to convert the image formats of all images in a folder using tkinter. all extensions I want in a combobox but I don't know why this code doesn't work .no error is displayed.
from tkinter import filedialog, StringVar
from tkinter import ttk
root=tkinter.Tk()
root.geometry("800x600")
#defining functions
def get_folder():
global folder_path
folder_path = filedialog.askdirectory(initialdir='./', title="Select Folder")
print(folder_path)
def get_extension():
change_to = com.get()
change_from = "py"
files=os.listdir(folder_path)
for file in files:
if (".%s"%change_from) in file:
newfile=file.replace((".%s"%change_from),".%s"%change_to)
os.rename((folder_path+'/'+file),(folder_path+'/'+newfile))
#defining widgets for frames
folder_label = tkinter.Label(from_frame)
browse_button = tkinter.Button(from_frame, text="Browse", command=get_folder)
change_button = tkinter.Button(button_frame, text="Change Extension", command=get_extension)
change_button.pack()
#defining combobox
com = StringVar()
list_combo = ['.png','.jpg','.jpeg', '.svg', '.tif','.bmp','.gif','ppm']
combox = ttk.Combobox(root, width = 25, font = 'arial 19 bold', value = list_combo, state = 'r', textvariable = com)
combox.place(x= 190, y= 190)
combox.set('select type')
root.configure(bg = 'coral1')
root.mainloop()```

Is this what You want:
from tkinter import Tk, Button, Label, StringVar, Frame
from tkinter.ttk import Combobox
from tkinter.filedialog import askdirectory
import os
def convert_extensions():
path = dir_lbl.cget('text')
from_ = from_var.get()
to_ = to_var.get()
files_from = [f'{path}/{file}' for file in os.listdir(path) if file.split('.')[-1] == from_]
files_to = ['.'.join(file.split('.')[:-1]) + '.' + file.split('.')[-1].replace(from_, to_) for file in files_from]
for from_file, to_file in zip(files_from, files_to):
os.rename(from_file, to_file)
print(f'{"-" * 100}\n'
f'{"From:": <10} {from_file}\n'
f'{"To:": <10} {to_file}\n')
root = Tk()
root.geometry('500x200')
Button(root, text='Choose Directory', command=lambda: dir_lbl.config(text=askdirectory())).pack(pady=5)
dir_lbl = Label(root, text='')
dir_lbl.pack(pady=5)
options_frame = Frame(root)
options_frame.pack(pady=5)
from_var = StringVar(value='Convert from')
list_combo = ['png', 'jpg', 'jpeg', 'svg', 'tif', 'bmp', 'gif', 'ppm']
Combobox(options_frame, value=list_combo,
textvariable=from_var, state='r').pack(side='left', padx=5, pady=5)
to_var = StringVar(value='Convert to')
Combobox(options_frame, value=list_combo,
textvariable=to_var, state='r').pack(side='left', padx=5, pady=5)
Button(root, text='Convert', command=convert_extensions).pack(pady=5)
root.mainloop()
This however allows more control in that You can choose both the extension to convert and to which one convert.
This is pretty basic so if You have any questions, ask. I will probably add a detailed explanation later but for now this is all I can do. Oh and btw that three line print function is not necessary at all and it probably should be made to display that in tkinter window or sth but otherwise it can be removed.

Related

tkinter change color of bg and fg while programme is running

I want to programme my own notepad. As a function, I want to be able to toggle between white mode and dark mode.
This is my code so far. I know that the problem is that the variables color_fg and color_bg are not transferred to the top, but I just can't find a solution for it.
import tkinter as tk
from tkinter import filedialog
color_fg = "#dbdbdb"
color_bg = "#282b33"
root = tk.Tk()
root.title("Improved Notepad)")
root.geometry("800x600")
text_widget = tk.Text(root, bg=color_bg, fg=color_fg)
text_widget.pack(fill=tk.BOTH, expand=True)
menu_bar = tk.Menu(root, bg=color_bg, fg=color_fg)
dark_mode = tk.BooleanVar(value=False)
# File menu
file_menu = tk.Menu(menu_bar, tearoff=0, bg=color_bg, fg=color_fg)
def open_text():
filepath = filedialog.askopenfilename()
with open(filepath, 'r') as f:
text = f.read()
text_widget.delete(1.0, tk.END)
text_widget.insert(1.0, text)
def save_text():
filepath = filedialog.asksaveasfilename(defaultextension=".txt")
text = text_widget.get(1.0, tk.END)
with open(filepath, 'w') as f:
f.write(text)
file_menu.add_command(label="Open", command=open_text)
file_menu.add_command(label="Save", command=save_text)
file_menu.add_command(label="Exit", command=root.quit)
menu_bar.add_cascade(label="File", menu=file_menu)
# Settings menu
def toggle_dark_mode():
if dark_mode.get():
color_fg = "#dbdbdb"
color_bg = "#282b33"
dark_mode.set(False)
else:
color_fg = "#000000"
color_bg = "#FFFFFF"
dark_mode.set(True)
settings_menu = tk.Menu(menu_bar, tearoff=0, bg=color_bg, fg=color_fg)
dark_mode_toggle = tk.Checkbutton(settings_menu, text="Dark Mode", variable=dark_mode, onvalue=True, offvalue=False)
settings_menu.add_checkbutton(label="Dark Mode", command=toggle_dark_mode)
menu_bar.add_cascade(label="Settings", menu=settings_menu)
root.config(menu=menu_bar)
root.mainloop()
You have to explicitly change the color in the widget. Also, you aren't associating the variable with the checkbutton menu item. You're associating it with a separate Checkbutton widget that you don't seem to use anywhere.
The following is a working version of your code, with the File menu and some other unnecessary code removed to keep the example short. The key points are:
the call to settings_menu.add_checkbutton adds the variable option to tie it to the variable
toggle_dark_mode explicitly changes the background and foreground options of the text widget.
import tkinter as tk
color_fg = "#dbdbdb"
color_bg = "#282b33"
def toggle_dark_mode():
if dark_mode.get():
text_widget.configure(foreground=color_fg, background=color_bg)
else:
text_widget.configure(foreground=color_bg, background=color_fg)
root = tk.Tk()
dark_mode = tk.BooleanVar(value=True)
text_widget = tk.Text(root, bg=color_bg, fg=color_fg)
text_widget.pack(fill=tk.BOTH, expand=True)
menu_bar = tk.Menu(root, bg=color_bg, fg=color_fg)
settings_menu = tk.Menu(menu_bar, tearoff=0, bg=color_bg, fg=color_fg)
settings_menu.add_checkbutton(label="Dark Mode", command=toggle_dark_mode, variable=dark_mode)
menu_bar.add_cascade(label="Settings", menu=settings_menu)
# sync the color mode with the menu
toggle_dark_mode()
root.config(menu=menu_bar)
root.mainloop()

Tkinter theme is not working, just displays as regular

I'm trying to use the theme "sun valley" for a python-based installer that i'm working on. I have all the .tcl files installed and everything should be working, but its not. I even tried to use the built in styles
here's my code:
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
import os
director = os.path.dirname(__file__)
friendlyName = "python"
file = ""
import shutil
global User
try:
User = os.getlogin()
except:
User="home"
from tkinter import *
from tkinter import filedialog
from os import path
path = fr"C:\{User}\AppData\Local\{friendlyName}"
def install():
try:
os.mkdir(path)
except:
pass
shutil.copy(file, path)
#E1 = Entry(top, bd =5)
window = Tk()
# Just simply import the azure.tcl file
style = ttk.Style(window)
dir_path = os.path.dirname(os.path.realpath(__file__))
window.tk.call('source', os.path.join(dir_path, 'theme\dark.tcl'))
print(os.path.join(dir_path, 'theme\dark.tcl'))
#window.tk.call("set_theme", "dark")
style.theme_use('sun-valley-dark')
window.geometry("600x400")
window.rowconfigure(20)
window.columnconfigure(20)
def askdir():
direct = filedialog.askdirectory()
path = direct
textBox.delete(0, END)
textBox.insert(0, path)
#textBox.set(path)
window.update_idletasks()
window.title(f"{friendlyName} install")
chooseText = Label(window, text=f"choose a place for {friendlyName} to be installed")
chooseText.grid(column=2, row=0)
chooseButton = Button(window, text="choose path", command=askdir)
chooseButton.grid(column=1, row=3)
textBox = Entry(window, text=f"{path}")
textBox.insert(0, path)
textBox.grid(column=2, row=3)
chooseButton = Button(window, text="install", command=install)
chooseButton.grid(column=3, row=4)
chooseButton = Button(window, text="quit", command=window.destroy)
chooseButton.grid(column=1, row=4)
window.mainloop()
heres what outputs:
Need to use ttk widgets
instead of chooseText = Label(window, text=f"choose a place for {friendlyName} to be installed")
it would be chooseText = ttk.Label(window, text=f"choose a place for {friendlyName} to be installed")
then the style will show up!

How to get file name from one functuion to work in another

I have 2 function (Upload and Calc): 1st open file and writing its name (using button); 2nd should work with data from this file (excel file, will also start after button pressed). 1st part working well, but 2nd I dont understand how to get file name from 1st function(that getting file) to work in 2nd fuction(that work with data in file).
import tkinter as tk
from tkinter import Label, Pack, filedialog
from tkinter.constants import CENTER, LEFT
from tkinter.filedialog import askopenfilename
from pathlib import Path
from openpyxl import Workbook
import os
global filename
def Upload():
filename = filedialog.askopenfilename()
filepath=filename
path=Path(filepath)
#print(path.name)
#вставить проверку расширения файла
label2 = Label(text=path.name, font="Arial 17", justify=LEFT)
label2.place(relx=0.35, rely=.13)
#print('Selected:', filename)
return(path.name)
def Calc():
workbook = load_workbook(filename=path.name)
root= tk.Tk()
canvas1 = tk.Canvas(root, width = 300, height = 300)
canvas1.pack()
button1 = tk.Button(text='Open File',command=Upload, bg='purple',fg='white')
button1.place (relx = 0.5, rely = 0.5, anchor=CENTER)
button2 = tk.Button(text='Calculate',command=Calc, bg='purple',fg='white')
button2.place (relx = 0.5, rely = 0.6, anchor=CENTER)
label1 = Label(text= 'Выбраный файл:', fg="#eee", bg="#333")
label1.place(relx = 0.5, y=20, anchor=CENTER)
canvas1.create_window(150, 150, window=button1)
root.mainloop()
Try making the variable path global:
def Upload():
global path
filename = filedialog.askopenfilename()
filepath=filename
path=Path(filepath)
#print(path.name)
#вставить проверку расширения файла
label2 = Label(text=path.name, font="Arial 17", justify=LEFT)
label2.place(relx=0.35, rely=.13)
#print('Selected:', filename)
return(path.name)
def Calc():
global path
workbook = load_workbook(filename=path.name)

Convert multiple images to pdf

I wanted to create a pdf converter app with python which converts images to pdf.
This is my code but it is only converting one image into pdf I tried many ways to fix it but none of them worked can anyone please help me because I want to convert multiple images into pdf but it is not working besides using for loop. I tried img2pdf but it giving alpha channel error and I am not able to solve that.
import PIL.Image
from tkinter import *
from tkinter import filedialog as fd
import PyPDF2
import img2pdf
from tkinter import ttk
root = Tk()
root.geometry('500x500')
root.resizable(0, 0)
filename = StringVar()
entry = Entry(root, width=50, textvariable=filename).place(x=115, y=250)
def Select_images():
global files
files = fd.askopenfilenames()
def select_dir():
global dir_name
dir_name = fd.askdirectory()
def submit():
global file_name
file_name = filename.get()
def create_pdf():
myfile=open(f'{dir_name}/{file_name}.pdf', 'wb+')
for image in files:
img=PIL.Image.open(image).convert('RGBA')
im1=img.convert('RGB')
im1.save(r'{}\{}.pdf'.format(dir_name,file_name))
myfile.close()
button = Button(root, text='Sumbit PDF Name', command=submit).place(x=200, y=300)
label = Label(root, text='Write PDF Name').place(x=210, y=215)
button1 = Button(root, text='Create File', command=create_pdf).place(x=215, y=335)
button2 = Button(root, text='Select Directory To Save File',command=select_dir).place(x=200, y=50)
button3 = Button(root, text='select Images', command=Select_images).place(x=235, y=100)
root.mainloop()
See if this helps you:
from tkinter import Tk, messagebox as mb, filedialog as fd
from tkinter.constants import DISABLED, NORMAL
from tkinter.ttk import Button, Label
from PIL import Image
import os
root = Tk()
root.title("Image to PDF converter")
root.geometry("500x500")
imglist = [] # For creating a list of images
fimgl = [] # List for storing multiple image names
png = True # If the image chosen is a .png file
def askfile():
global files, fimg, order, imglist, tm, png
files = fd.askopenfilenames(title="Choose images", filetypes=(("PNGs", "*.png"), ("JPGs", "*.jpg"), ("All Files", "*.*")))
for i in files:
fimgl.append(i)
if files:
for j in fimgl:
if j.endswith(".png"): # If the image is a PNG:
png = True
fnl = Label(root, text=j)
fnl.pack()
img = Image.open(j)
fimg = img.convert('RGB')
imglist.append(fimg)
p.config(state=NORMAL)
def convert_pdf():
global png
try:
if png:
imglist.pop()
saveloc = fd.asksaveasfilename(title="Save the PDF file")
if saveloc:
if saveloc.endswith(".pdf"):
pass
else:
saveloc = saveloc + ".pdf"
if os.path.exists(saveloc):
yn = mb.askyesno("Confirm Save As", f"{os.path.basename(saveloc)} already exists.\nDo you want to replace it?")
if yn:
os.remove(saveloc)
else:
convert_pdf()
fimg.save(saveloc, save_all=True, append_images=imglist)
mb.showinfo("Done!", "PDF file saved! Click 'OK' to open it")
os.startfile(saveloc)
root.quit()
except Exception as err:
mb.showerror("Error", err)
root.quit()
cb = Button(root, text="Add Files", command=askfile)
cb.pack(pady=20)
p = Button(root, text="Convert", command=convert_pdf, state=DISABLED)
p.pack(pady=20)
root.mainloop()

Get the entry directory as a string in Tkinter Python

I am trying to make a Windows software using Tkinter from Python, the purpose of this app is to move specific types of files to a specified directory.
But the error comes here, it looks like that my move function ins't getting my entry text and also the extension text, so thats why I think there is the error, the code is here....
import tkinter.filedialog as filedialog
import tkinter as tk
import os
import shutil
def input_source():
input_path = tk.filedialog.askdirectory()
input_entry.delete(1, tk.END) # Remove current text in entry
input_entry.insert(0, input_path) # Insert the 'path'
def output():
output_path = tk.filedialog.askdirectory()
output_entry.delete(1, tk.END) # Remove current text in entry
output_entry.insert(0, output_path) # Insert the 'path'
def move():
files = os.listdir(input_entry.get())
for file in files: # for every file in the source directory
file_name, extension = os.path.splitext(file) # lets split the name of the file and its extension
if extension == f".{file_extension.get()}": # knowing what type of extension or type of file, lets just move
# those
# files to the new directory
shutil.move(f"{input_entry.get()}/{file}", output_entry.get())
else: # if there are any files with that extension, lets just pass\skip\terminate the process
pass
master = tk.Tk()
top_frame = tk.Frame(master)
bottom_frame = tk.Frame(master)
line = tk.Frame(master, height=1, width=400, bg="grey80", relief='groove')
# input path
input_path = tk.Label(top_frame, text="Input File Path:")
input_entry = tk.Entry(top_frame, text="", width=40)
browse1 = tk.Button(top_frame, text="Browse", command=input_source)
# output path
output_path = tk.Label(bottom_frame, text="Output File Path:")
output_entry = tk.Entry(bottom_frame, text="", width=40)
browse2 = tk.Button(bottom_frame, text="Browse", command=output)
# File extension
file_extension_ = tk.Label(bottom_frame, text="File type:")
file_extension = tk.Entry(bottom_frame, text="", width=40)
file_extension.insert(0, 'Type file extension: .')
move = tk.Button(bottom_frame, text='Move!', command=move)
top_frame.pack(side=tk.TOP)
line.pack(pady=10)
bottom_frame.pack(side=tk.BOTTOM)
input_path.pack(pady=5)
input_entry.pack(pady=5)
browse1.pack(pady=5)
output_path.pack(pady=5)
output_entry.pack(pady=5)
browse2.pack(pady=5)
file_extension.pack(pady=5)
file_extension.pack(pady=5)
move.pack(pady=20, fill=tk.X)
master.mainloop()
Simplify this and it should work. If you're just trying to move files to the typed path, why not do it this way?
from tkinter import *
import os
root = Tk()
root.title("File Mover")
def move_file():
firstpath = entry1.get()
secondpath = entry2.get()
os.replace(firstpath, secondpath)
label1 = Label(text="Enter File Directory to Move")
label2 = Label(text="Enter New File Directory")
entry1 = Entry(width=20, justify="center")
entry2 = Entry(width=20, justify="center")
button = Button(text="Move File", command=move_file)
label1.grid(row=0, column=0)
label2.grid(row=1,column=0)
entry1.grid(row=0,column=1)
entry2.grid(row=1, column=1)
button.grid(row=2,column=0)
root.mainloop()
this requires they include the name of the file in the path, but I guarantee that it will get the text, and that it works moving the files on my machine.

Categories

Resources