modify text file with tkinter python3 - python-3.x

How can i modify text (Add or delete) file which i opened with Tkinter?
For example when i open some file with notebad i can easily modify text.
I cant figure out how can i do it in tkinter.
There is my code:
from tkinter import *
from tkinter import filedialog
import re
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.master.title("JoNotepad")
self.pack(fill=BOTH, expand=1)
menu = Menu(top)
top.config(menu=menu)
self.file_menu = Menu(menu)
menu.add_cascade(label="File", menu=self.file_menu)
self.file_menu.add_command(label="New")
self.file_menu.add_command(label="Open", command=self.open_file_function)
self.file_menu.add_command(label="Save")
self.file_menu.add_separator()
self.file_menu.add_command(label="Exit")
self.listNodes = Listbox(top, height=200, width=200)
self.listNodes.pack(side=LEFT, fill=Y, expand=True)
self.scrollbar = Scrollbar(top, orient="vertical")
self.scrollbar.config(command=self.listNodes.yview)
self.scrollbar.pack(side=RIGHT, fill=Y, expand=True)
self.listNodes.config(yscrollcommand=self.scrollbar.set)
def open_file_function(self):
self.file_save = filedialog.askopenfilename(initialdir = "/", title = "Select file", filetypes = (("txt files", "*.txt"), ("All files", "*.*")))
with open(self.file_save) as file:
for i in file:
self.listNodes.insert(END, i)
top = Tk()
top.geometry("1000x1000")
ap = Window(top)
top.mainloop()

You should use the tkinter Text widget instead of the Listbox. The Text widget allows you to perform want you want to do (including add text, delete text, select text, etc).
Here is your code, using the Text widget.
from tkinter import *
from tkinter import filedialog
import re
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.master.title("JoNotepad")
self.pack(fill=BOTH, expand=1)
menu = Menu(top)
top.config(menu=menu)
self.file_menu = Menu(menu)
menu.add_cascade(label="File", menu=self.file_menu)
self.file_menu.add_command(label="New")
self.file_menu.add_command(label="Open", command=self.open_file_function)
self.file_menu.add_command(label="Save")
self.file_menu.add_separator()
self.file_menu.add_command(label="Exit")
self.text = Text(top, height=200, width=200) #Use Text widget insted of Listbox
self.text.pack(side=LEFT, fill=Y, expand=True)
self.scrollbar = Scrollbar(top, orient="vertical")
self.scrollbar.config(command=self.text.yview)
self.scrollbar.pack(side=RIGHT, fill=Y, expand=True)
# change all occurances of self.listNodes to self.text
self.text.config(yscrollcommand=self.scrollbar.set)
def open_file_function(self):
self.file_save = filedialog.askopenfilename(initialdir = "/", title = "Select file", filetypes = (("txt files", "*.txt"), ("All files", "*.*")))
with open(self.file_save) as file:
for i in file:
self.text.insert(END, i)
top = Tk()
top.geometry("1000x1000")
ap = Window(top)
top.mainloop()

Related

Tkinter - label doesn't update

This morning I started to work on a little app so I can understand better TkInter.
I didn't get too far because I can't make the label to update after I press a button.
It seems like after I create an instance of the Label object I can't work on it anymore because of the mainloop() I guess? I tried to use .update() and other ways to make this work but I can't figure it out. If I add () to file_explorer method, the label updates but I can't open the file explorer anymore and it also starts the file explorer without pressing the button so it's pointless. Found something here on StackOverflow but still nothing.
from tkinter import *
from tkinter import filedialog as fd
import os
# Main_window
App = Tk()
App.geometry("300x300")
App.resizable(0, 0)
filename = "empty"
class Btn:
def __init__(self, master, pos_x, pos_y, label):
frame = Frame(master)
frame.pack()
self.Button = Button(master, text=label, command=self.file_explorer)
self.Button.place(x=pos_x, y=pos_y)
def file_explorer(self):
global filename
filename = fd.askopenfilename(filetypes=(('text files', '*.txt'), ('All files', '*.*')))
filename = os.path.basename(filename)
class FileLabel:
def __init__(self, master, pos_x, pos_y):
global filename
frame = Frame(master)
frame.pack()
self.label1 = Label(master, text=filename)
self.label1.place(x=pos_x, y=pos_y)
e = Btn(App, 10, 10, "Browse file")
f = FileLabel(App, 90, 12)
App.mainloop()
Updating filename will not update the label automatically. However, you can use StringVar instead of normal string and textvariable option of Label to achieve the goal:
...
filename = StringVar(value="empty")
class Btn:
def __init__(self, master, pos_x, pos_y, label):
frame = Frame(master)
frame.pack()
self.Button = Button(master, text=label, command=self.file_explorer)
self.Button.place(x=pos_x, y=pos_y)
def file_explorer(self):
fname = fd.askopenfilename(filetypes=(('text files', '*.txt'), ('All files', '*.*')))
# update filename
filename.set(os.path.basename(fname))
class FileLabel:
def __init__(self, master, pos_x, pos_y):
frame = Frame(master)
frame.pack()
self.label1 = Label(master, textvariable=filename) # used textvariable instead
self.label1.place(x=pos_x, y=pos_y)
...

How to show images from path in new window in python tk

After browsing path of image i wanna show image on next window in python using Tk library but image is not showing in next window. please take a look on my code below and give answer Thanks.
import tkinter as tk
from tkinter import filedialog as fd
a=""
str1 = "e"
class Browse(tk.Frame):
""" Creates a frame that contains a button when clicked lets the user to select
a file and put its filepath into an entry.
"""
def __init__(self, master, initialdir='', filetypes=()):
super().__init__(master)
self.filepath = tk.StringVar()
self._initaldir = initialdir
self._filetypes = filetypes
self._create_widgets()
self._display_widgets()
def _create_widgets(self):
self._entry = tk.Entry(self, textvariable=self.filepath, font=("bold", 10))
a=self._entry
self._button = tk.Button(self, text="Browse...",bg="red",fg="white", command=self.browse)
self._classify=tk.Button(self,text="Classify",bg="red",fg="white", command=self.classify)
self._label=tk.Label(self, text="IMAGE CLASSIFICATION USING DEEP LERAINING.", bg="blue", fg="white",height=3, font=("bold", 14))
def _display_widgets(self):
self._label.pack(fill='y')
self._entry.pack(fill='x', expand=True)
self._button.pack(fill='y')
self._classify.pack(fill='y')
def retrieve_input(self):
#str1 = self._entry.get()
#a=a.replace('/','//')
print (str1)
def classify(self):
newwin = tk.Toplevel(root)
newwin.geometry("500x500")
label = tk.Label(newwin, text="Classification", bg="blue", fg="white",height=3, font=("bold", 14))
label.pack()
canvas = tk.Canvas(newwin, height=300, width=300)
canvas.pack()
my_image = tk.PhotoImage(file=a, master=root)
canvas.create_image(150, 150, image=my_image)
newwin.mainloop()
def browse(self):
""" Browses a .png file or all files and then puts it on the entry.
"""
self.filepath.set(fd.askopenfilename(initialdir=self._initaldir,
filetypes=self._filetypes))
if __name__ == '__main__':
root = tk.Tk()
labelfont = ('times', 10, 'bold')
root.geometry("500x500")
filetypes = (
('Portable Network Graphics', '*.png'),
("All files", "*.*")
)
file_browser = Browse(root, initialdir=r"C:\Users",
filetypes=filetypes)
file_browser.pack(fill='y')
root.mainloop()
Your global variable a which stores the path of the image is not getting updated. You need to explicitly do it. Below is the code that works. Have a look at the browse() function.
import tkinter as tk
from tkinter import filedialog as fd
a=""
str1 = "e"
class Browse(tk.Frame):
""" Creates a frame that contains a button when clicked lets the user to select
a file and put its filepath into an entry.
"""
def __init__(self, master, initialdir='', filetypes=()):
super().__init__(master)
self.filepath = tk.StringVar()
self._initaldir = initialdir
self._filetypes = filetypes
self._create_widgets()
self._display_widgets()
def _create_widgets(self):
self._entry = tk.Entry(self, textvariable=self.filepath, font=("bold", 10))
a = self._entry
self._button = tk.Button(self, text="Browse...",bg="red",fg="white", command=self.browse)
self._classify=tk.Button(self,text="Classify",bg="red",fg="white", command=self.classify)
self._label=tk.Label(self, text="IMAGE CLASSIFICATION USING DEEP LERAINING.", bg="blue", fg="white",height=3, font=("bold", 14))
def _display_widgets(self):
self._label.pack(fill='y')
self._entry.pack(fill='x', expand=True)
self._button.pack(fill='y')
self._classify.pack(fill='y')
def retrieve_input(self):
#str1 = self._entry.get()
#a=a.replace('/','//')
print (str1)
def classify(self):
global a
newwin = tk.Toplevel(root)
newwin.geometry("500x500")
label = tk.Label(newwin, text="Classification", bg="blue", fg="white",height=3, font=("bold", 14))
label.pack()
canvas = tk.Canvas(newwin, height=300, width=300)
canvas.pack()
my_image = tk.PhotoImage(file=a, master=root)
canvas.create_image(150, 150, image=my_image)
newwin.mainloop()
def browse(self):
""" Browses a .png file or all files and then puts it on the entry.
"""
global a
a = fd.askopenfilename(initialdir=self._initaldir, filetypes=self._filetypes)
self.filepath.set(a)
if __name__ == '__main__':
root = tk.Tk()
labelfont = ('times', 10, 'bold')
root.geometry("500x500")
filetypes = (
('Portable Network Graphics', '*.png'),
("All files", "*.*")
)
file_browser = Browse(root, initialdir=r"~/Desktop", filetypes=filetypes)
file_browser.pack(fill='y')
root.mainloop()
P.S. Do change your initialdir. I changed it as I am not on Windows.

How can i create a Modal Dialogue Box by messagebox.showerror

How can I create a Modal Dialogue Box by messagebox.showerror?
messagebox.showerror("Error", "No downloader.exe found")
When I create a messagebox, I found I can move the root windows.
and i need to create a Modal Dialogue Box like filedialog.askopenfilename.
filedialog.askopenfilename(initialdir = self.get_path()+ '/bin', filetypes=[("BIN Files", ".bin")])
here's the codes:
import tkinter
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import os
class Application(Frame):
def createWidgets(self, main_frame):
#self.llabel = Label(main_frame, text="Ready", width=20, bg="turquoise", font = ftLabel)
#self.llabel.grid(row=0, column=0, sticky=W+E) #columnspan=2
self.frame1 = Frame(main_frame)
self.frame1.grid(row=0, column=0, columnspan=2, sticky=W+E+N+S)
self.addr = StringVar()
self.addrtext = Entry(self.frame1, width=20, textvariable = self.addr)
self.addrtext.grid(row=0, column=0, sticky=W+E+N+S)
self.addr.set("0x0")
self.bfile = Button(self.frame1, text='BIN File', width=20)
self.bfile.grid(row=0, column=1, sticky=W+E+N+S)
messagebox.showerror("Error", "No downloader.exe found")
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack(fill=BOTH, expand=1)
main_frame = Frame(master)
main_frame.pack(fill="y", expand=1)
self.createWidgets(main_frame)
self.dl_thread = 0
if __name__=="__main__":
root = Tk()
#lock the root size
root.resizable(False,False)
app = Application(master=root)
app.mainloop()
I tried your code and messagebox.showerror is modal to me.
Maybe there is something else in your code (threads?) or maybe it's
dependent on your environment.
For reference, my entire code:
from tkinter import *
from tkinter import messagebox
root = Tk()
def do(): messagebox.showerror("Error", "No downloader.exe found")
b = Button(root, text='Dialog', command=do)
b.pack()
root.mainloop()
If that doesn't work you might want to take a look at: Tkinter messagebox not behaving like a modal dialog

How do i change the font in my text editor from the font menu

from tkinter import *
import tkinter.filedialog
from tkinter import ttk
class TextEditor:
#staticmethod
def quit_app(event=None):
root.quit()
def change_font(self, event=None):
print(text_font.get())
def open_file(self, event=None):
txt_file = tkinter.filedialog.askopenfilename(parent=root, initialdir="C:/Users/Cesar/PycharmProjects")
if txt_file:
self.text_area.delete(1.0, END)
with open(txt_file) as _file:
self.text_area.insert(1.0, _file.read())
root.updata_idletasks()
def save_file(self, event=None):
file = tkinter.filedialog.asksaveasfile(mode='w')
if file != None:
data = self.text_area.get(1.0, END + '-1c')
file.write(data)
file.close()
def __init__(self, root):
self.text_to_write = ""
root.title("Text Editor")
root.geometry("600x500")
frame = Frame(root, width=600, height=500)
scrollbar = Scrollbar(frame)
self.text_area = Text(frame, width=600, height=500, yscrollcommand=scrollbar.set, padx=10, pady=10)
scrollbar.config(command=self.text_area.yview)
scrollbar.pack(side=RIGHT, fill="y")
self.text_area.pack(side="left", fill="both", expand=True)
frame.pack()
the_menu = Menu(root)
# ---------- file menu -------------
file_menu = Menu(the_menu, tearoff=0)
file_menu.add_command(label="Open",command=self.open_file)
file_menu.add_command(label="Save", command=self.save_file)
file_menu.add_separator()
file_menu.add_command(label="Quit", command=self.quit_app())
the_menu.add_cascade(label="File", menu=file_menu)
# ---------- format menu and font menu--------
"""
font_menu = Menu(the_menu, tearoff=0)
text_font = StringVar()
text_font.set("Times")
def change_font():
style = ttk.Style()
style.configure(self.text_area, font = text_font)
print("Font picked: ", text_font.get())
font_menu = Menu(the_menu, tearoff=0)
font_menu.add_radiobutton(label="Times", variable=text_font, command=change_font)
font_menu.add_radiobutton(label="Arial", variable=text_font, command=change_font)
font_menu.add_radiobutton(label="Consoles", variable=text_font, command=change_font)
font_menu.add_radiobutton(label="Courier", variable=text_font, command=change_font)
font_menu.add_radiobutton(label="Tahoma", variable=text_font, command=change_font)
the_menu.add_cascade(label="Fonts", menu=font_menu)
"""
root.config(menu=the_menu)
root = Tk()
text_edit = TextEditor(root)
root.mainloop()
i put the code for the font menu in a comment to make sure the program is working
ttk.Style is used to style objects from ttk, which Text is not. To set the font on a tkinter.Text widget you need to use tkinter.font.Font.
import tkinter.font
#...
def __init__(self):
# ...
# ---------- format menu and font menu--------
self.text_font = StringVar()
self.text_font.set("Times")
font_menu = Menu(the_menu, tearoff=0)
self.fonts = {}
for font in ("Times","Arial", "Consoles", "Courier", "Tahoma"):
self.fonts[font] = tkinter.font.Font(font=font)
font_menu.add_radiobutton(label=font, variable=self.text_font, command=self.change_font)
the_menu.add_cascade(label="Fonts", menu=font_menu)
root.config(menu=the_menu)
def change_font(self):
self.text_area.config(font = self.fonts[self.text_font.get()])
BTW a scrolled Text widget is built into tkinter in the ScrolledText widget.

How to add background image to my application in Tkinter?

The code picture needs to fit the screen size perfectly. I saw a bunch of tutorials but nothing seems to work.I tried adding a canvas but it covers half the screen.All my buttons go under the image itself not over it. It's getting on my nerves .
here's my code :
import tkinter as tk
import PIL
from PIL import Image, ImageTk
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
root = Tk()
w = Label(root, text="Send and receive files easily")
w.config(font=('times', 32))
w.pack()
def create_window():
window = tk.Toplevel(root)
window.geometry("400x400")
tower= PhotoImage(file="D:/icons/tower.png")
towlab=Button(root,image=tower, command=create_window)
towlab.pack()
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title("Bifrost v1.0")
self.pack(fill=BOTH, expand=1)
self.img1 = PhotoImage(file="D:/icons/download.png")
self.img2 = PhotoImage(file="D:/icons/upload.png")
sendButton = Button(self, image=self.img2)
sendButton.place(x=305, y=15)
receiveButton = Button(self, image=self.img1)
receiveButton.place(x=355, y=15)
menu = Menu(self.master)
self.master.config(menu=menu)
file = Menu(menu)
file.add_command(label='Exit', command=self.client_exit)
menu.add_cascade(label='File', menu=file)
edit = Menu(menu)
edit.add_command(label='abcd')
menu.add_cascade(label='Edit', menu=edit)
help = Menu(menu)
help.add_command(label='About Us', command=self.about)
menu.add_cascade(label='Help', menu=help)
def callback():
path = filedialog.askopenfilename()
e.delete(0, END) # Remove current text in entry
e.insert(0, path) # Insert the 'path'
# print path
w = Label(root, text="File Path:")
e = Entry(root, text="")
b = Button(root, text="Browse", fg="#a1dbcd", bg="black", command=callback)
w.pack(side=TOP)
e.pack(side=TOP)
b.pack(side=TOP)
def client_exit(self):
exit()
def about(self):
top = Toplevel()
msg = Message(top, text="This is a project developed by Aditi,Sagar and
Suyash as the final year project.",
font=('', '15'))
msg.pack()
top.geometry('200x200')
button = Button(top, text="Okay", command=top.destroy)
button.pack()
top.mainloop()
root.resizable(0,0)
#size of the window
root.geometry("700x400")
app = Window(root)
root.mainloop()
Overlaying elements is tricky. I think this might be approximately what you're looking for. At least it's a start...
import PIL
from PIL import Image, ImageTk
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
root = Tk()
class Window:
def __init__(self, master=None):
tower = PIL.Image.open("Images/island.png")
master.update()
win_width = int(master.winfo_width())
win_height = int(master.winfo_height())
# Resize the image to the constraints of the root window.
tower = tower.resize((win_width, win_height))
tower_tk = ImageTk.PhotoImage(tower)
# Create a label to hold the background image.
canvas = Canvas(master, width=win_width, height=win_height)
canvas.place(x=0, y=0, anchor='nw')
canvas.create_image(0, 0, image=tower_tk, anchor='nw')
canvas.image = tower_tk
frame = Frame(master)
frame.place(x=win_width, y=win_height, anchor='se')
master.update()
w = Label(master, text="Send and receive files easily", anchor='w')
w.config(font=('times', 32))
w.place(x=0, y=0, anchor='nw')
master.title("Bifrost v1.0")
self.img1 = PhotoImage(file="Images/logo.png")
self.img2 = PhotoImage(file="Images/magnifier.png")
frame.grid_columnconfigure(0, weight=1)
sendButton = Button(frame, image=self.img2)
sendButton.grid(row=0, column=1)
sendButton.image = self.img2
receiveButton = Button(frame, image=self.img1)
receiveButton.grid(row=0, column=2)
receiveButton.image = self.img1
menu = Menu(master)
master.config(menu=menu)
file = Menu(menu)
file.add_command(label='Exit', command=self.client_exit)
menu.add_cascade(label='File', menu=file)
edit = Menu(menu)
edit.add_command(label='abcd')
menu.add_cascade(label='Edit', menu=edit)
help = Menu(menu)
help.add_command(label='About Us', command=self.about)
menu.add_cascade(label='Help', menu=help)
def callback():
path = filedialog.askopenfilename()
e.delete(0, END) # Remove current text in entry
e.insert(0, path) # Insert the 'path'
# print path
w = Label(root, text="File Path:")
e = Entry(root, text="")
b = Button(root, text="Browse", fg="#a1dbcd", bg="black", command=callback)
w.pack(side=TOP)
e.pack(side=TOP)
b.pack(side=TOP)
def client_exit(self):
exit()
def about(self):
message = "This is a project developed by Aditi,Sagar and"
message += "Suyash as the final year project."
messagebox.showinfo("Delete Theme", message)
root.resizable(0,0)
#size of the window
root.geometry("700x400")
app = Window(root)
root.mainloop()

Resources