Corrupted image in tkinter asksaveasfile - python

I tried to make a pop-up save qr code image window using asksaveasfile, but it gives me a corrupted image file.
This is what happens if you open it
My code:
root = Tk()
root.geometry("400x350")
root.title("QR Code Generator")
label = Label(text="QR Code Generator", fg="black", font="NexaHeavy")
label.pack(pady=20)
link_entry = Entry()
link_entry.insert(0, 'Link')
link_entry.pack(pady=50)
name_entry = Entry()
name_entry.insert(0, 'QR Code name')
name_entry.pack(pady=50)
def savefile():
asksaveasfile(defaultextension='*.jpg', filetypes=[
("All types", '.*'),
("JPG File", ".jpg")
])
# Generate QR Code
def make():
qr_code = qrcode.make(link_entry.get())
qr_codename = (f"{name_entry.get()}.png")
qr_code.save(qr_codename, savefile())
make_button = Button(text="Make QR Code", command=make)
make_button.pack(pady=1)
root.mainloop()

If you want to use asksaveasfile() to select the output filename, you should not construct the filename using qr_codename = (f"{name_entry.get()}.png"):
def savefile():
# return the selected file object
return asksaveasfile(defaultextension='*.jpg', filetypes=[
("All types", '.*'),
("JPG File", ".jpg")
], mode="wb") # must use binary mode for image data
# Generate QR Code
def make():
qr_codename = savefile()
if qr_codename:
qr_code = qrcode.make(link_entry.get())
qr_code.save(qr_codename)

Related

button change its text to the file name

How do I force the button to change its text to the filename? Everything works fine, a dialog box opens and files open too. But I still can't change the button name to the file name and save it.
Here is the code:
import tkinter.filedialog as tfd
import tkinter as tk
import os
window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)
file_name = ""
def open():
global file_name
file_name = tfd.askopenfilename()
os.startfile(file_name) #open file
btn1 = tk.Button(window, text=f"Open {file_name}", command=open) #button
btn1.place(x = 20, y = 25)
You can set the buttons text property using.
button['text'] = fileName
You can also read the button text propeerty to make sure it has been set to the file name in code, I.e. with an if statement.
bText = button['text']
Try using .config -
import tkinter.filedialog as tfd
import tkinter as tk
import os
window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)
file_name = ""
def open():
global file_name
file_name = tfd.askopenfilename()
btn1.config(text=file_name) # Configure the button's text
os.startfile(file_name) #open file
btn1 = tk.Button(window, text=f"Open {file_name}", command=open) #button
btn1.place(x = 20, y = 25)
But if you run this code, the button name gets changed to the complete pathname (e.g. - C:/.../Choosen.file), so if you want only the file name ('Choosen.file') then use this -
btn1.config(text=file_name.split('/')[-1])
You can use:
window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)
file_name = ""
def open():
global file_name
file_name = tfd.askopenfilename()
btn1["text"] += " '" + file_name + "'"
os.startfile(file_name)
btn1 = tk.Button(window, text="Open file", command=open) # button
btn1.place(x=20, y=25)
tk.mainloop()
This uses the old text of the button and appends '{file_path}' to it -> Open file '{file_path}'
You could define a new class that maintains state. This way you can avoid the global, and will be able to make multiple buttons each with their own files.
class FileButton(tk.Button):
def __init__(self, window, file_name=""):
super().__init__(window, command=self.open)
self.set_text(file_name)
def set_text(self, file_name):
self.file_name = file_name
self["text"] = f"Open {self.file_name}"
def open(self):
if self.file_name == "":
self.set_text(tfd.askopenfilename())
os.startfile(self.file_name)
window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)
btn1 = FileButton(window)
btn1.place(x=20, y=25)
window.mainloop()

Tkinter why cant copy text from textbox?

so i made a program that can convert pdf file to text bu then I make it into a gui so that its easier for a user but when it work I wasn't able to copy the text from the text box is there something wrong with my code or did I do something wrong pls help
import PyPDF2
import tkinter as tk
from tkinter import filedialog
from tkinter import *
def browseFiles():
file = filedialog.askopenfilename(initialdir = "/",title = "Select a Pdf File", filetypes = (("PDF files","*.pdf"),("all files","*.*")))
print(file)
return file
#Graphical User Interface
root = tk.Tk()
root.title('Pdf to text')
root.geometry('600x400')
#Upload pdf
tLabel = tk.Label(root, text='PDF to Text Converter')
tLabel.pack()
textFile = tk.Text(root, height=20, width=70)
textFile.config(bg='#dddddd')
textFile.pack()
button_explore = Button(root,
text = "Browse Files",
command = browseFiles,)
button_explore.pack()
button_exit = Button(root,
text = " Exit ",
command = exit)
button_exit.pack()
file = browseFiles()
pdfFileObj = open(file, "rb")
# create reader variable that will read the pdffileobj
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
# This will store the number of pages of this pdf file
x = pdfReader.numPages
# create variable that will select the selected number of pages
# x+1 because python indentation start from 0
pageObj = pdfReader.getPage(x - 1)
# create text variable which will store all text data from pdf file
textObj = pageObj.extractText()
textFile.config(state='normal')
textFile.delete('1.0', 'end')
textFile.insert('1.0', textObj)
textFile.config(state='disabled')
root.mainloop()

Open file and get file path

I'm trying to create a button to browse file and copy that file to a Master file and my code as below:
from tkinter import *
from tkinter import filedialog
def get_file_path():
global file_path
file_path= filedialog.askopenfilename(title = "Select A File", filetypes = (("xlsx", "*.xlsx"), ("xls", "*.xls"), ("xlsm", "*.xlsm"), ("All Files", "*.*")))
l1 = Label(window, text = file_path).pack()
window = Tk()
b1 = Button(window, text = "Open File", command = get_file_path).pack()
window.mainloop()
def close_window():
window.destroy()
print(file_path)
import openpyxl as xl
path1 = ("r'" and file_path)
path2 = (r'C:\Users\...\Write_Data.xlsx')
wb1 = xl.load_workbook(filename=path1)
ws1 = wb1["BASEL_LN_CTR"]
wb2 = xl.load_workbook(filename=path2)
ws2 = wb2["Loan Data"]
for row in ws1:
for cell in row:
ws2[cell.coordinate].value = cell.value
wb2.save(path2)
Everything is working well for me but I have to close window manually to print file_path. I would like to know that there is any way to close window aucomatically. I used destroy() but it not worked.
You created close_window() but you never use it.
You could create another button to run it (or to run directly window.destroy)
window = tk.Tk()
b1 = tk.Button(window, text="Open File", command=get_file_path).pack()
b2 = tk.Button(window, text="Close", comman=window.destroy).pack()
window.mainloop()
Or you should run it directly in get_file_path()
def get_file_path():
global file_path
file_path = filedialog.askopenfilename(title="Select A File", filetypes = (("xlsx", "*.xlsx"), ("xls", "*.xls"), ("xlsm", "*.xlsm"), ("All Files", "*.*")))
if file_path: # empty when pressed `Cancel`
#tk.Label(window, text=file_path).pack()
window.destroy()

can't insert default text into TKinter

So I am creating a text editor using TKinter. I have the basics down and now I am trying to create a button where when you press it, you select a file and it opens it. From what I have seen the insert method would be best for Entry widget. But i am using Label widget and it does not work for some reason. Here is my code so far:
import sys
import tkinter as tk
frame = tk.Tk()
frame.title("Fake Google Docs")
frame.geometry('800x600')
inputtxt = tk.Text(frame,
height = 25,
width = 90)
inputtxt.pack()
global file
#this is function to be executed when u press first button
def printInput():
filename = input("Name of the file make sure you end with .txt")
file = open(filename, 'w')
result=inputtxt.get("1.0","end")
file.write(result)
file.close()
#this is function to be executed for open new file thing
def printInputnew():
filenamemm = input("Name of the file make sure you end with .txt")
file = open(filenamemm, 'w')
result=inputtxt.get("1.0","end")
file.write("")
file.close()
def openfile():
filenamem = input("Name of the file you want to open")
tru=open(filenamem)
if tru== False:
sys.exit()
else:
f = open(filenamem, "r")
for x in f:
print(x)
name=str(x)
text = tk.StringVar()
text.set(name)
#button 1
printButton = tk.Button(frame,
text = "Save to text file",
command = printInput)
printButton.pack()
printButtonl = tk.Button(frame,
text = "open a file",
command = openfile)
printButtonl.pack()
#button 2
printButton = tk.Button(frame,
text = "Open new file",
command = printInputnew)
printButton.pack()
#open the text box
lbl = tk.Label(frame, textvariable = "")
lbl.pack()
#finish code
frame.mainloop()
Could someone else suggest a method for inserting text into this widget?
Here it is:
import sys
import tkinter as tk
from tkinter import filedialog
frame = tk.Tk()
frame.title("Fake Google Docs")
frame.geometry('800x600')
inputtxt = tk.Text(frame,
height=25,
width=90)
inputtxt.pack()
global file
mask = [("Text and Python files", "*.txt *.py *.pyw *.rcad"),
("HTML files", "*.htm"),
("All files", "*.*")]
# this is function to be executed when u press first button
def printInput():
filename = input("Name of the file make sure you end with .txt")
file = open(filename, 'w')
result = inputtxt.get("1.0", "end")
file.write(result)
file.close()
# this is function to be executed for open new file thing
def printInputnew():
filenamemm = input("Name of the file make sure you end with .txt")
file = open(filenamemm, 'w')
result = inputtxt.get("1.0", "end")
file.write("")
file.close()
def openfile():
filenamem = filedialog.askopenfilename(filetypes=mask)
tru = open(filenamem)
if tru == False:
sys.exit()
else:
f = open(filenamem, "r")
inputtxt.delete(0.0, 'end')
inputtxt.insert('end', f.read())
# button 1
printButton = tk.Button(frame,
text="Save to text file",
command=printInput)
printButton.pack()
printButtonl = tk.Button(frame,
text="open a file",
command=openfile)
printButtonl.pack()
# button 2
printButton = tk.Button(frame,
text="Open new file",
command=printInputnew)
printButton.pack()
# open the text box
lbl = tk.Label(frame, textvariable="")
lbl.pack()
# finish code
frame.mainloop()
I changed this block of code:
def openfile():
filenamem = filedialog.askopenfilename(filetypes=mask)
tru = open(filenamem)
if tru == False:
sys.exit()
else:
f = open(filenamem, "r")
inputtxt.delete(0.0, 'end')
inputtxt.insert('end', f.read())
It opens a window that ask you which file you want to open. askopenfilename method returns a string path to selected file. Then you just read whole file, delete whole text that you had in your tk.Text object and paste there text from opened file. That is all :)
And please, next time watch some guides about tkinter before asking and read about PEP8.

PIL Python Module throwing error when saving image with Tkinter

Whenever I try to save an image selected from tkinter, I get an error like this:
raise ValueError("unknown file extension: {}".format(ext)) from e
ValueError: unknown file extension:
I'm using tkinter to open up the file browser to select an image file. The user can choose to flip the image horizontally and vertically. After that, they can choose to save as a variety of image formats. However, this returns the above error. I don't really see what is wrong. The name variable in the save() function contains the name after the file is picked. PIL's save function should be able to take that name and save it in the current working directory.
from tkinter import *
from tkinter import filedialog
from PIL import Image
def open_image():
global img
img = Image.open(
filedialog.askopenfilename(title="Select file", filetypes=(("jpeg files", "*.jpg"), ("all files", "*.*"))))
save_button.config(bg=default_color)
flip_horizontal_button.config(bg=default_color)
flip_vertical_button.config(bg=default_color)
def flip_horizontal():
global img
if img:
img = img.transpose(Image.FLIP_LEFT_RIGHT)
def flip_vertical():
global img
if img:
img = img.transpose(Image.FLIP_TOP_BOTTOM)
def save():
global img
if img:
#os.chdir("/")
default_name = "Untitled"
""" print(default_name+"."+img.format)
print(os.path.isfile(default_name+"."+img.format))
print(os.path)
if os.path.isfile(default_name+"."+img.format):
expand = 1
while True:
expand += 1
expanded_name = default_name+str(expand)
if os.path.isfile(expanded_name):
continue
else:
default_name = expanded_name
break"""
name = filedialog.asksaveasfilename(title="Save As", filetypes=(
('JPEG', ('*.jpg', '*.jpeg', '*.jpe')), ('PNG', '*.png'), ('GIF', '*.gif')),
initialfile=default_name+"."+img.format)
img.save(name)
img = None
root = Tk()
root.title("Meme Deep Fryer")
root.geometry('600x500')
default_color = root.cget('bg')
open_button = Button(text='Open Image', font=('Arial', 20), command=open_image)
flip_horizontal_button = Button(text='Flip Horizontal', font=('Arial', 10), command=flip_horizontal, bg="gray")
flip_vertical_button = Button(text='Flip Vertical', font=('Arial', 10), command=flip_vertical, bg="gray")
save_button = Button(text='Save', font=('Arial', 20), command=save, bg="gray")
open_button.pack(anchor='nw', side=LEFT)
save_button.pack(anchor='nw', side=LEFT)
flip_horizontal_button.pack(anchor='w')
flip_vertical_button.pack(anchor='w')
root.mainloop()
You could pass argument typevariable in asksaveasfilename:
ext = tkinter.StringVar()
name = filedialog.asksaveasfilename(title="Select file", typevariable=ext, filetypes=(('JPEG', ('*.jpg', '*.jpeg', '*.jpe')), ('PNG', '*.png'), ('BMP', ('*.bmp', '*.jdib')), ('GIF', '*.gif')))
if name:
img.save(os.path.basename(name)+"."+ext.get().lower()) # splice the string and the extension.

Categories