How do i change the font in my text editor from the font menu - python-3.x

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.

Related

how to fix borders please

i did this mini programme to show databases to the user , i can see buttons of databases but when i press on them borders appear on canvas
from tkinter import *
from tkinter import ttk
import mysql.connector
class mainpro():
def __init__(self):#its my database settings
self.db = mysql.connector.connect(
host="localhost",
user="root",
port=3306,
passwd="1234"
)
self.mycursor = self.db.cursor()
win2 = Toplevel()#idid top level because i did tk before
# Title
win2.title('Manipulate Database')
# geometry
sizex = 1000
sizey = 700
posx = 100
posy = 100
win2.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))
# style
style = ttk.Style()
style.theme_use('vista')
style.configure('TLabel', font=('Calibri', 15))
style.configure('TButton', font=('Calibri', 15, 'bold'))
# menu
menu = Menu(win2)
m1 = Menu(menu, tearoff=0)
menu.add_cascade(label='File', menu=m1)
m2 = Menu(menu, tearoff=0)
menu.add_cascade(label='DLL', menu=m2)
m3 = Menu(menu, tearoff=0)
menu.add_cascade(label='DML', menu=m3)
m4 = Menu(menu, tearoff=0)
menu.add_cascade(label='Help', menu=m4)
m1.add_command(label='Show databases', command=lambda: showdata())
win2.config(menu=menu)
def showdata():
def event(event):
canvas.config(scrollregion=canvas.bbox("all"))
self.mycursor.execute('SHOW DATABASES')
list = self.mycursor.fetchall()
canvas = Canvas(win2, width=1000, height=700)
f1 = Frame(canvas)
canvas.create_window((0, 0), window=f1, anchor='nw')
scroll = Scrollbar(win2, orient="vertical", command=canvas.yview)
scroll.pack(side="right", fill="y")
canvas.configure(yscrollcommand=scroll.set)
canvas.pack()
f1.bind("<Configure>", event)
y = 0
for x in list:
y += 1
ttk.Label(f1, text=str(y) + '-').grid(column=0, row=y, padx=10, pady=10, sticky='w')
ttk.Button(f1, text=x, width=35).grid(column=1, row=y, padx=10, pady=10, sticky='w')
win2.mainloop()
mainpro()
help please
You could try adding highlightthickness=0:
canvas = Canvas(win2, width=1000, height=700, highlightthickness=0)
Try this,
Source: Check
import tkinter # assuming Python 3 for simplicity's sake
import tkinter.ttk as ttk
root = tkinter.Tk()
f = tkinter.Frame(relief='flat')
lF = ttk.LabelFrame(root, labelwidget=f, borderwidth=4)
lF.grid()
b = ttk.Button(lF, text='')
b.grid()
root.mainloop()
Or try this
Canvas=Canvas(self,width=width/2,height=height/2,bg=bgCanvasColor,borderwidth=0, highlightthickness=0)

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

modify text file with tkinter python3

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

migrate tkinter code to pyqt

I am trying to migrate the code below (which is in tkinter) to pyqt. I am very new to pyqt. I could not get much details.
import os, sys, time
import os.path
import shutil
import sys
import Tkinter as tk
from Tkinter import *
root = Tk()
frame = Frame(root)
def enable_():
# Global variables
if (var.get()==1):
E5.config(state=NORMAL)
E5.insert(0, 1)
for c in checkbuttons:
c.config(state=NORMAL)
# disable test selection
else:
E5.delete(0, END)
E5.config(state=DISABLED)
for c in checkbuttons:
c.config(state=DISABLED)
# Select geometry
root.geometry("500x570+500+300")
root.title('Test Configure')
# Global variable declaration
global row_me
global col_me
row_me =9
col_me =0
L1 = Label ().grid(row=0,column=1)
Label (text='Target IP Address').grid(row=1,column=0)
E4 = Entry(root, width=20)
E4.grid(row=1,column=1)
L1 = Label ().grid(row=2,column=1)
variable = StringVar()
# Check button creation
var = IntVar()
var_mail = IntVar()
# Create check buttons
R1=Checkbutton(root, text = "Enable Test Suite Selection", variable = var, \
onvalue = 1, offvalue = 0, height=1, \
width = 20, command=enable_)
R1.grid(row=3,column=1)
R2=Checkbutton(root, text = "Send Email", variable = var_mail, \
onvalue = 1, offvalue = 0, height=1, \
width = 20)
R2.grid(row=3,column=2)
L5 = Label (text='Number of Loop').grid(row=4,column=0)
E5 = Entry(root, width=5)
E5.grid(row=4,column=1)
E5.config(state=DISABLED)
L2 = Label ().grid(row=21,column=1)
# List of Tests
bottomframe = Frame(root)
bottomframe.grid(row=24,column=1)
# Reset Button
configbutton = Button(bottomframe, text="Reset", fg="black")
configbutton.grid(row=24,column=2,padx=5, pady=0)
# Quit Button
configbutton = Button(bottomframe, text="Quit", fg="red")
configbutton.grid(row=24,column=3)
# Submit Button
blackbutton = Button(bottomframe, text="Submit", fg="black")
blackbutton.grid(row=24,column=4,padx=5, pady=0)
#Check buttons for test suite selection
test_suite_name=[name for name in os.listdir(".") if (os.path.isdir(name) and name.startswith('test-') )]
L34 = Label (text='Select Test Suite To Be Executed').grid(row=7,column=1)
L11 = Label ().grid(row=9,column=1)
row_me =9
col_me =0
checkbuttons = [create_checkbutton(name) for name in test_suite_name ]
for c in checkbuttons:
c.config(state=DISABLED)
# initiate the loop
root.mainloop()
I have written this code but I am not sure how to make the grid and location for each widget in pyqt:
import sys
from PyQt4 import QtGui
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
SubmitButton = QtGui.QPushButton("OK")
CancelButton = QtGui.QPushButton("Cancel")
ResetButton = QtGui.QPushButton("Reset")
edit1 = QLineEdit()
edit2 = QLineEdit()
cb = QtGui.QCheckBox('Enable Test suite selection', self)
cb.move(150, 100)
#cb.stateChanged.connect(self.changeTitle)
cb2 = QtGui.QCheckBox('Send mail', self)
cb2.move(300, 100)
# cb2.stateChanged.connect(self.changeTitle)
hbox = QtGui.QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(SubmitButton)
hbox.addWidget(CancelButton)
hbox.addWidget(ResetButton)
hbox.addWidget(edit1)
hbox.addWidget(edit2)
hbox.addWidget(cb)
hbox.addWidget(cb2)
vbox = QtGui.QVBoxLayout()
vbox.addStretch(1)
vbox.addLayout(hbox)
self.setLayout(vbox)
self.setGeometry(100, 100, 500, 650)
self.setWindowTitle('HMI')
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Thank you!
You can either do the designing part in your code or through a QT Designer which ships with PyQt4. and some examples can be found in the path C:\Python26\Lib\site-packages\PyQt4\examples and documentation in the path C:\Python26\Lib\site-packages\PyQt4\doc\html\modules.html if you are using windows. Hope this helps.

Resources