How do I send send text from the label to entry box, or send directly the path of the image to entry box in tkinter?
from tkinter import *
from PIL import ImageTk,Image
from tkinter import filedialog
root = Tk()
def open():
root.filename = filedialog.askopenfilename(initialdir="/", title="Select A File",filetypes=(("jpg files", "*.jpg"), ("all files", "*.*")))
my_label = Label(root, text=root.filename).pack()
my_btn = Button(root, text="Open files", command=open).pack()
#entry box
txt2 = Entry(root)
txt2.place(x=10, y=45)
root.mainloop()
Did you mean get text in label and insert the text to an Entry?
If yes, you can just make a StringVar() in the Entry
For example like this:
from tkinter import * #For python 3
from Tkinter import * #For python 2
root = Tk()
txt = StringVar()
#For inserting text
txt.set("This is a label and an entry")
label = Label(root, textvariable=txt).pack()
entry = Entry(root, textvariable=txt).pack()
root.mainloop()
Related
I have made a pdf viewer using tkinter. I am wondering if I can let the pdf file 'pop out' using Toplevel() function. I tried to use lambda to try to incorporate the Toplevel() when using the button but the pop out window did not reflect anything. Here is the code I made:
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkPDFViewer import tkPDFViewer as pdf
import os
#make tk case
root = Tk()
root.geometry("1000x700+200+100")
root.title("PDF Viewer")
root.configure(bg="light blue")
#view frame
view_frame=Frame(root, bg="light blue", bd=5, width=400)
view_frame.pack(side=LEFT)
#to generate pop up window to view PDFs
def popup(filename):
win=Toplevel()
win.geometry("100x80")
win.title(filename)
v2=None
file = ''
#search for files
def viewpdf():
#make v2 global
global v2
filename=filedialog.askopenfilename(initialdir=os.getcwd(),
title="Select PDF File",
filetype=(("PDF File", ".pdf"),
("PDF File", ".PDF"),
("All File",".txt")))
if filename:
global file
file=filename
#destroy old file if it exists
if v2:
v2.destroy()
#create new pdf images
v1=pdf.ShowPdf()
#clear stored images
v1.img_object_li.clear()
#store new images
v2=v1.pdf_view(view_frame, pdf_location=open(filename,"r"),height=50, width=80)
v2.pack(pady=(0,0))
#set buttons
view_button=Button(view_frame, text='SEARCH FOR FILES', command=lambda: [viewpdf(), popup(file)], width=50, bd=5)
view_button.pack()
root.mainloop()
Update: I have tried adding tkinter.TopLevel() inside the def viewpdf() and it worked! I have deleted the def popup() as well.
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkPDFViewer import tkPDFViewer as pdf
import os
#make tk case
root = Tk()
root.geometry("1000x700+200+100")
root.title("PDF Viewer")
root.configure(bg="light blue")
#view frame
view_frame=Frame(root, bg="light blue", bd=5, width=400)
view_frame.pack(side=LEFT)
v2 = None
#search for files
def viewpdf():
#make v2 global
global v2
filename=filedialog.askopenfilename(initialdir=os.getcwd(),
title="Select PDF File",
filetype=(("PDF File", ".pdf"),
("PDF File", ".PDF"),
("All File",".txt")))
if filename:
#destroy old file if it exists
if v2:
v2.destroy()
#create new pdf images
v1=pdf.ShowPdf()
#clear stored images
v1.img_object_li.clear()
#set a new pop out window
newWindow=tkinter.Toplevel(view_frame)
#store new images
v2=v1.pdf_view(newWindow, pdf_location=filename, height=50, width=80)
v2.pack(pady=(0,0))
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()
How do I use user input to retrieve an image, and display it on the screen? I have the user input field in Tkinter, and I do not know how to get that to go to my folder, and get the image to show up on the same screen.
EDIT: I was able to get the path to show on the screen, but now I don't know how to get the actual image to show up from that path inside the frame... I do not know how to link this path to have the program display the image, i.e. myimage1 from my folder.
from tkinter import *
from PIL import ImageTk,Image
from tkinter import ttk
from tkinter import filedialog
root = Tk()
root.title("Images")
root.iconbitmap(r'C:\Users\hadhikari\example\Takumi_Logo.ico')
button_quit = Button(root, text= "Exit Program", command=root.quit)
button_quit.pack()
e= Entry(root, width=50, bg="light blue", borderwidth=3)
e.pack()
e.insert(0," ")
def myClick():
link = "r'C:\\Users\\hadhikari\\example\\" + e.get()
myLabel1 = Label(root, text=link)
myLabel1.pack()
myButton = Button(root, text="Scan Part Number", command=myClick,
bg="pink", fg="white")
myButton.pack()
#my_img = ImageTk.PhotoImage(Image.open('link'))
#my_Label = Label(image=my_img)
#my_Label.pack()
#def getText():
# inputtedtext = entrybox.get()
#entrybox = Entry(root)
#entrybox.pack()
#btn = Button(root, text="Submit", command=getText)
#btn.pack()
frame = LabelFrame(root, padx=100, pady=100)
frame.pack(padx=50, pady=50)
root.mainloop()
As suggested in the comments, maybe using Tkinter's askopenfilename dialog might be a better choice than hardcoding the filepath, and letting the user input the filename.
But, first of all, let's fix the code following your intentions. Most of the part on how to properly set up a Tkinter Label, and dynamically place images in that, can be easily found, for example in this Q&A. Basically, you want to put the "update routine" inside your myClick method:
from tkinter import *
from PIL import Image, ImageTk
# How to properly set up Tkinter label with dynamically changeable
# ImageTk.PhotoImage: https://stackoverflow.com/a/3482156/11089932
root = Tk()
button_quit = Button(root, text='Exit Program', command=root.quit)
button_quit.pack()
e = Entry(root, width=50, bg='light blue', borderwidth=3)
e.pack()
e.insert(0, '')
my_label = Label()
my_label.pack()
def myClick():
link = r'your/path/goes/here' + e.get()
my_img = ImageTk.PhotoImage(Image.open(link))
my_label.configure(image=my_img)
my_label.image = my_img
myButton = Button(root, text='Scan Part Number', command=myClick,
bg='pink', fg='white')
myButton.pack()
root.mainloop()
Program at startup:
Opening the first image:
Opening another image:
Now, regarding the askopenfilename dialog, we get rid of the Entry widget, and simply open the dialog inside the myClick method:
from tkinter import *
from tkinter.filedialog import askopenfilename
from PIL import Image, ImageTk
# How to properly set up Tkinter label with dynamically changeable
# ImageTk.PhotoImage: https://stackoverflow.com/a/3482156/11089932
root = Tk()
button_quit = Button(root, text='Exit Program', command=root.quit)
button_quit.pack()
my_label = Label()
my_label.pack()
def myClick():
link = askopenfilename()
my_img = ImageTk.PhotoImage(Image.open(link))
my_label.configure(image=my_img)
my_label.image = my_img
myButton = Button(root, text='Scan Part Number', command=myClick,
bg='pink', fg='white')
myButton.pack()
root.mainloop()
Program at startup:
Opening the first image (dialog):
Opening the first image (display):
----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.19041-SP0
Python: 3.9.1
PyCharm: 2021.1.3
Pillow: 8.3.1
----------------------------------------
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.
I am stating to develop a program in which you click a button with the text "open" on it, and it will bring up a file selection window using filedialog.askopenfilename, but the button won't appear, and it will automatically bring up the window without the button needing to be pressed. Here is the code:
from tkinter import *
from tkinter import filedialog
root = Tk()
root.title("Snake converter")
sim = filedialog.askopenfilename(filetypes = (("Snake files", "*.sim"),("Python Files", "*.py"),("All files", "*.*")))
openbutton = Button(root, text = "Open", width = 10, command = sim)
Nowhere in your code you're calling a geometry manager(pack, grid, place etc.) so your button isn't shown. Also filedialog.askopenfilename runs immediately even if it's assigned to an object. I am also unsure that you can call an object as button function. Try the following:
def sim():
filedialog.askopenfilename(filetypes = (("Snake files", "*.sim"),("Python Files", "*.py"),("All files", "*.*")))
openbutton = Button(root, text = "Open", width = 10, command=sim)
openbutton.pack()
root.mainloop()
also your code should look like:
from tkinter import *
from tkinter import filedialog
root = Tk()
root.title("Snake converter")
def sim():
filedialog.askopenfilename(filetypes = (("Snake files", "*.sim"),("Python Files", "*.py"),("All files", "*.*")))
openbutton = Button(root, text = "Open", width = 10, command=sim)
openbutton.pack()
root.mainloop()
I'd also check frequent questions as a newcomer to tkinter.