I'm new to python GUI and I'm going to display my result but I have some problem with displaying it.
I put the whole code but I have a problem with the def blur(file_path) function. here is my code :
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
import cv2 as cv
# =================================== statics and configuration ===================================
color = '#20536C'
root = Tk()
root.title('Opticdisk and Macula detector')
root.configure(bg= color)
root.geometry('1070x700')
root.resizable(width=False, height=False)
root.iconbitmap('J:\Projects\Bachelor Project\download.ico')
filename_path = {}
# =================================== Frames ===================================
top = Frame(root, width=1070, height=70,pady = 9, bg=color)
top.pack(side=TOP)
# top.grid(row = 0 , column= 1)
left = Frame(root, width=750, height=630, bg=color)
left.pack(side=LEFT)
# left.grid(row = 1 , column= 1)
right = Frame(root, width=320, height=630, bg="red")
right.pack(side=LEFT)
# =================================== functions and body ===================================
img1 = ImageTk.PhotoImage(Image.open('J:/Projects/Bachelor Project/eye.ico'))
def open_image(file_path):
file_path['image'] = filedialog.askopenfilename(initialdir="J://uni//final project//Data set",
title="select an image",
filetypes=(('all files', '*.*'), ('jpg files', '*.jpg'), ('tif file','*.tif')))
mainImage = ImageTk.PhotoImage(Image.open(filename_path['image']))
lbl = Label(left, image=mainImage,
width= 749,
height=630,
bg='#020101')#.place(x=20, y=0)
lbl.image = mainImage # keep a reference! to show the image
lbl.place(x=0, y=0)
def blur(file_path):
# messagebox = Message(left).place(x=20,y=10)
try:
Im = cv.imread(file_path['image'])
I = cv.medianBlur(Im,15)
I = cv.resize(I, (300, 300))
canvas = Canvas(left, width=749, height=630)
# canvas.place(x=0, y=0)
# canvas.pack()
# canvas.create_image(20, 20, anchor=NW, image=I)
# canvas.image = I
canvas.pack()
cv.imshow('result', I)
cv.waitKey()
except:
print('error')
# =================================== Buttons ===================================
btnBrowse = Button(top, width=93,
text='select file',
fg='#58859a',
font=('Times', 15, 'italic', 'bold'),
bg='#03283a',
command = lambda :open_image(filename_path))
btnBrowse.pack(side=BOTTOM)
btnMask = Button(right, text='Opticdisk',
fg= '#58859a',
font=('Times', 20, 'italic', 'bold'),
bg="#03283a",
width=19,
height=6,
command=lambda: blur(filename_path))
btnMask.pack(side=TOP)
btnMakula = Button(right, text='Makula',
fg= '#58859a',
font=('Times', 20, 'italic', 'bold'),
bg="#03283a",
width=19,
height=6)
btnMakula.pack(side=TOP)
btnClear = Button(right, text='exit',
fg= '#58859a',
font=('Times', 20, 'italic', 'bold'),
bg="#03283a",
width=19,
height=6,
command=root.quit)
btnClear.pack(side=TOP)
root.mainloop()
I'm going to display I. As you can see in the comments I try canvas but it shows nothing but a white screen
OpenCV library shows the picture I with no problem as I want in the line cv.imshow('result', I) but I want to display it inside the program.
I would be appreciated if you guys help me?
as I'm in a hurry I found a solution for my above problem
I just save the resulting photo I and then put the address of the file in a dictionary path['image'] and open it with the same way we open folders in function open_image(file_path) here is my solution :
def blur(file_path):
path={}
# messagebox = Message(left).place(x=20,y=10)
try:
Im = cv.imread(file_path['image'])
I = cv.medianBlur(Im,15)
I = cv.resize(I, (300, 300))
# here is the solution
cv.imwrite('J://uni//final project//res_image//finalresult.jpg',I)
path['image'] = ('J://uni//final project//res_image//finalresult.jpg')
mainImage = ImageTk.PhotoImage(Image.open(path['image']))
lbl = Label(left, image=mainImage,
width=749,
height=630,
bg='#020101') # .place(x=20, y=0)
lbl.image = mainImage # keep a reference! to show the image
lbl.place(x=0, y=0)
#cv.imshow('result', I)
#cv.waitKey()
except:
print('error')
Related
Need to add an image as the frame background, the button quit must be on the image.I tried some codes but the image appeared as above and the frame below the image.
from tkinter import *
from tkinter import font
from PIL import ImageTk,Image
root = Tk()
root.title("Sign In")
root.geometry("600x420")
class one:
def __init__(self, root):
self.root = root
self.frame = Frame(self.root, bg="light blue", width=800, height=400)
root.geometry("800x400")
self.header = Label(self.root, bg="blue", fg="white", font=("Times New Roman", 30, "bold"))
self.header.pack(fill=X)
self.heading = Label(self.root, text="First One", fg="white", bg="blue", font=("Times New Roman", 30, "bold"))
self.heading.place(x=10, y=0)
self.q = Button(self.frame, text="Quit", bg="brown", fg="white", font=("Times New Roman", 10), command=self.root.destroy)
self.q.place(x=650, y=320, width=120, height=20)
self.frame.pack()
obj = one(root)
root.mainloop()
In Tkinter, you can add a background image to a frame by adding a label as the frame parent. Set the label background image using PIL and set the frame background to empty string.
Try this code.
from tkinter import *
from tkinter import font
from PIL import ImageTk,Image
root = Tk()
root.title("Sign In")
root.geometry("600x420")
class one:
def __init__(self, root):
self.root = root
self.img = ImageTk.PhotoImage(Image.open("bgredgrad.png")) # label image (frame background)
self.label = Label(self.root, image = self.img, width=800, height=400) # frame parent
self.frame = Frame(self.label, bg="", width=800, height=400) # main widget, clear background
self.frame.place(x=0, y=0, width=800, height=400) # required for correct z-index
root.geometry("800x400")
self.header = Label(self.root, bg="brown", fg="white", font=("Times New Roman", 30, "bold"))
self.header.pack(fill=X)
self.heading = Label(self.root, text="First One", bg="brown", fg="white", font=("Times New Roman", 30, "bold"))
self.heading.place(x=10, y=0)
self.q = Button(self.frame, text="Quit", bg="brown", fg="white", font=("Times New Roman", 10), command=self.root.destroy)
self.q.place(x=650, y=320, width=120, height=20)
self.label.pack() # pack bottom widget
obj = one(root)
root.mainloop()
Output (my background)
Very simple, don't be impressed by the size of the code.
I want to do something very simple (well, not for me, since I'm asking for help here) put the location of the open file in the red square on the screen:
Screen
import tkinter as tk
from tkinter.filedialog import askopenfilename
from tkinter import messagebox
def OpenFile_AntiDuplicate():
global antiduplicate_file
mainframe = tk.Frame(bg='#1c2028')
antiduplicate_file = askopenfilename(initialdir="/",
filetypes =(("Text file", "*.txt"),("All files","*.*")),
title = "Open text file"
)
fichier_dir = tk.Label(mainframe, text=antiduplicate_file).pack()
try:
with open(antiduplicate_file,'r') as UseFile:
print(antiduplicate_file)
except:
print("Non-existent file")
def RUN_AntiDuplicate():
try:
with open(antiduplicate_file,'r') as UseFile:
print(antiduplicate_file)
except:
error1 = tk.messagebox.showerror("ERROR", "No files exist!")
#----------------------------------------------------------
class HoverButton(tk.Button):
def __init__(self, master, **kw):
tk.Button.__init__(self,master=master,**kw)
self.defaultBackground = self["background"]
self.bind("<Enter>", self.on_enter)
self.bind("<Leave>", self.on_leave)
def on_enter(self, e):
self['background'] = self['activebackground']
def on_leave(self, e):
self['background'] = self.defaultBackground
#----------------------------------------------------------
def Anti_Duplicate():
mainframe = tk.Frame(bg='#1c2028')
mainframe.grid(row=0, column=0, sticky='nsew')
bouton_1 = HoverButton(mainframe, font=("Arial", 10), text="Back",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#CF3411',
relief='ridge', command=mainframe.destroy)
bouton_1.place(x=520, y=300)
open_button = HoverButton(mainframe, font=("Arial", 10), text="Open File..",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#1195cf',
relief='ridge', command = OpenFile_AntiDuplicate)
open_button.place(x=284.3, y=200, anchor='n')
run_button = HoverButton(mainframe, font=("Arial", 20), text="RUN",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#11CF6D',
relief='ridge', command = RUN_AntiDuplicate)
run_button.place(x=50, y=330, anchor='s')
bouton_2 = tk.Button(mainframe, font=("Arial", 10),
text="The purpose of this tool is to remove duplicate lines from a text file.",
background='#202124', fg='#1195cf', borderwidth=2,
activebackground= '#202124', activeforeground='#1195cf', relief='sunken')
bouton_2.place(relx=.5, y=50, anchor='n')
bouton_1 = tk.Button(mainframe, font=("Arial", 15), text="Anti-Duplicate",
background='#202124', fg='#1195cf', borderwidth=2,
activebackground='#202124', activeforeground='#1195cf', relief='sunken')
bouton_1.pack(side= "top", padx= 5, pady=5, ipadx= 30, anchor="n")
#----------------------------------------------------------
def main_menu():
root = tk.Tk()
screenn_x = int(root.winfo_screenwidth())
root.config(background='#1c2028')
screenn_y = int(root.winfo_screenheight())
root.title("ComboKit v0.0.1")
root.minsize(570, 340)
root.resizable(0,0)
windowss_x = 570
windowss_y = 340
possX = (screenn_x // 2) - (windowss_x // 2)
possY = (screenn_y // 2) - (windowss_y // 2)
geoo = "{}x{}+{}+{}".format(windowss_x, windowss_y, possX, possY)
root.geometry(geoo)
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
mainframe = tk.Frame(root, bg='#1c2028')
mainframe.grid(row=0, column=0, sticky='n')
main_fusion_bouton = HoverButton(mainframe, font=("Arial", 15), text="Fusion",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#1195cf',
relief='ridge', command=None)
main_fusion_bouton.pack(side= "left", padx= 5, pady=5, ipadx= 10, anchor="n")
main_antiduplicate_bouton = HoverButton(mainframe, font=("Arial", 15), text="Anti-Duplicate",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#1195cf',
relief='ridge', command=Anti_Duplicate)
main_antiduplicate_bouton.pack(side= "left", padx= 5, pady=5, ipadx= 30)
main_split_button = HoverButton(mainframe, font=("Arial", 15), text="Split",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#1195cf',
relief='ridge', command=None)
main_split_button.pack(side= "left", padx= 5, pady=5, ipadx= 19, anchor="n")
root.mainloop()
main_menu()
So here's my code allows you to use 3 tools:
"Split" / "Anti-Duplicate" / "Merge"
At the moment I'm working on the "Anti-Duplicate" so it's on this Frame() where the text should be displayed.
I've already done everything, even the button to open the file explorer, but for the moment the location of the file is only displayed in the cmd.
Thank you very much!
The location of the file does not show up because you created a new frame to hold the label fichier_dir inside OpenFile_AntiDuplicate() and you did not call any layout function on the frame, so the frame will not be shown.
Better create the label fichier_dir inside Anti_Duplicate() and pass it to OpenFile_AntiDuplicate() function:
def Anti_Duplicate():
...
fichier_dir = tk.Label(mainframe, bg='#1c2028', fg='white')
fichier_dir.place(relx=0.5, y=170, anchor='n')
open_button = HoverButton(mainframe, font=("Arial", 10), text="Open File..",
background='#000000', fg='white', borderwidth=2,
activebackground='#202124', activeforeground='#1195cf',
relief='ridge', command = lambda: OpenFile_AntiDuplicate(fichier_dir))
...
And update OpenFile_AntiDuplicate(...):
def OpenFile_AntiDuplicate(fichier_dir):
global antiduplicate_file
antiduplicate_file = askopenfilename(initialdir="/",
filetypes =(("Text file", "*.txt"),("All files","*.*")),
title = "Open text file"
)
fichier_dir['text'] = antiduplicate_file
...
I am trying to update the label text in "label_enter_what" in accordance to what they chose in "drop". So if they choose "Energy", the label would change to: Enter wavelength in chosen unit below", for example. Sorry if the code looks messy, it's my first time coding. This is supposed to be a photon property calculator that i am making for fun because in physics we are currently doing this, but with pens and calculators.
import tkinter as tk
from tkinter import *
from PIL import ImageTk, Image
HEIGHT = 600
WIDTH = 900
root = tk.Tk()
root.title("Photon property calculator")
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()
background_image = ImageTk.PhotoImage(Image.open('interference.jpg'))
background_label = tk.Label(root, image=background_image)
background_label.place(relheight=1, relwidth=1)
frame = tk.Frame(root, bg='#3E3E3E', bd=5)
frame.place(relx=0.5, rely=0.1, relheight=0.1, relwidth=0.75, anchor='n')
frame_upper = tk.Frame(root, bg='#3E3E3E', bd=5)
frame_upper.place(relx=0.5, rely=0.03, relheight=0.06, relwidth=0.75, anchor='n')
label_what_to_calc = tk.Label(frame_upper, bg='white', text='Enter what \n to calculate')
label_what_to_calc.place(relx=0, rely=0, relheight=1, relwidth=0.15)
label_enter_what = tk.Label(frame_upper, bg='white', text='Enter * in a chosen unit below.')
label_enter_what.place(relx=0.2, relheight=1, relwidth=0.2)
label_unit = tk.Label(frame_upper, bg='white', text='')
label_unit.place(relx=0.5, relheight=1, relwidth=0.1)
lower_frame = tk.Frame(root, bg='#60A8FF', bd=10)
lower_frame.place(relx=0.5, rely=0.3, relheight=0.5, relwidth=0.75, anchor='n')
entry_value = tk.Entry(frame, font=40, bg='white')
entry_value.place(relx=0.175, rely=0, relheight=1, relwidth=0.4)
OPTIONS = [
"Energy",
"Frequency",
"Wavelength"
]
clicked = StringVar()
clicked.set(OPTIONS[0])
drop = tk.OptionMenu(frame, clicked, *OPTIONS)
drop.place(relx=0, rely=0, relheight=1, relwidth=0.15)
OPTIONS_UNITS = ["μm",
"nm",
"pm",
"aJ",
"zJ",
]
clicked_1 = StringVar()
clicked_1.set(OPTIONS_UNITS[1])
drop_units = tk.OptionMenu(frame, clicked_1, *OPTIONS_UNITS)
drop_units.place(relx=0.6, rely=0, relheight=1, relwidth=0.09)
button = tk.Button(frame, text='Calculate!', font=40, bg="#F96612", fg='black')
button.place(relx=0.7, relheight=1, relwidth=0.3)
label = tk.Label(lower_frame, bg='white', text=clicked.get())
label.place(relheight=1, relwidth=1)
root.mainloop()
You can use
tk.OptionMenu( ... command=function)
to run function which will get selected value and it will change text in label
import tkinter as tk
# --- functions ---
def on_select(value):
label['text'] = value
# --- main ---
root = tk.Tk()
label = tk.Label(root, text='?')
label.pack()
OPTIONS = ["Energy", "Frequency", "Wavelength"]
value_var = tk.StringVar(value=OPTIONS[0])
op = tk.OptionMenu(root, value_var, *OPTIONS, command=on_select)
op.pack()
root.mainloop()
I need help. I need to bring out the image background to my new created frame in genkeymenu function. But the problem is, once the frame is created, the image background only seems to change in the first created frame. I tried to search for solutions but nothing works. Can I ask what's the problem?
import Tkinter as tk
from Tkinter import *
from PIL import Image, ImageTk
def genkeymenu():
generatemenu = tk.Toplevel(mainmenu)
bg1 = ImageTk.PhotoImage(file="key2.jpg")
background_label = Label(image=bg1)
background_label.place(x=0, y=0)
background_label.image = bg1
keynamelabel = Label(generatemenu, text="Enter your key name")
keynameEntry = Entry(generatemenu)
keynameButton = Button(generatemenu, text="Enter")
check1024= Checkbutton(generatemenu, text="1024 bit")
check2048= Checkbutton(generatemenu, text="2048 bit")
check4096= Checkbutton(generatemenu, text="4096 bit")
tk.background_label.grid(row=0)
keynamelabel.grid(row=0)
keynameEntry.grid(row=1)
keynameButton.grid(row=2)
check1024.grid(row=3, column=0)
check2048.grid(row=3, column=1)
check4096.grid(row=3, column=2)
generatemenu.title("Generate Key")
generatemenu.mainloop()
mainmenu = tk.Tk()
bg = ImageTk.PhotoImage(file="key.jpg")
background_label = Label(image=bg)
background_label.place(x=0, y=0)
genkeybutton = Button(mainmenu, text= "Generate Key Pair", fg="black", command=genkeymenu)
encryptbutton = Button(mainmenu, text= "Encrypt your message", fg="black")
decryptbutton = Button(mainmenu, text= "Decrypt your message", fg="black")
background_label.grid(row=0)
genkeybutton.grid(row=0, column=0, sticky = N, rowspan=2)
encryptbutton.grid(row=0, column=0)
decryptbutton.grid(row=0, column=0, sticky=S)
mainmenu.title("RSA ENCRYPTION")
mainmenu.mainloop()
You specify all the widget to appear in the toplevel window but didn't do that for the background. background_label = Label(generatemenu, image=bg1)
import Tkinter as tk
from Tkinter import *
PIL import Image, ImageTk
def genkeymenu():
generatemenu = tk.Toplevel(mainmenu)
bg1 = ImageTk.PhotoImage(file="key2.jpg")
background_label = Label(generatemenu, image=bg1)# specify the window you it to appear.
background_label.place(x=0, y=0)
background_label.image = bg1
keynamelabel = Label(generatemenu, text="Enter your key name")
keynameEntry = Entry(generatemenu)
keynameButton = Button(generatemenu, text="Enter")
check1024= Checkbutton(generatemenu, text="1024 bit")
check2048= Checkbutton(generatemenu, text="2048 bit")
check4096= Checkbutton(generatemenu, text="4096 bit")
tk.background_label.grid(row=0)
keynamelabel.grid(row=0)
keynameEntry.grid(row=1)
keynameButton.grid(row=2)
check1024.grid(row=3, column=0)
check2048.grid(row=3, column=1)
check4096.grid(row=3, column=2)
generatemenu.title("Generate Key")
generatemenu.mainloop()
mainmenu = tk.Tk()
bg = ImageTk.PhotoImage(file="key.jpg")
background_label = Label(image=bg)
background_label.place(x=0, y=0)
genkeybutton = Button(mainmenu, text= "Generate Key Pair", fg="black",
command=genkeymenu)
encryptbutton = Button(mainmenu, text= "Encrypt your message", fg="black")
decryptbutton = Button(mainmenu, text= "Decrypt your message", fg="black")
background_label.grid(row=0)
genkeybutton.grid(row=0, column=0, sticky = N, rowspan=2)
encryptbutton.grid(row=0, column=0)
decryptbutton.grid(row=0, column=0, sticky=S)
mainmenu.title("RSA ENCRYPTION")
mainmenu.mainloop()
I don't understand what is going on. I have defined 2 functions. 1 function displays text, entry boxes, and a submit button. I have it so that when the submit button is pressed, it prints the information the user put inside of the entry boxes. I've shortened my code for easier readability.
from tkinter import *
from PIL import Image, ImageTk
canvas_width = 360
canvas_height = 525
file = r"C:\Users\kraak\Desktop\PyCharm Community Edition 2017.1.2\borderedpaper.GIF"
master = Tk()
canvas = Canvas(master, width=canvas_width, height=canvas_height)
old_img = PhotoImage(file=file)
new_img = old_img.subsample(3, 3)
canvas.create_image(-11, -10, anchor=NW, image=new_img)
canvas.create_window(0, 0, height=1, width=1, anchor=NW)
canvas.create_text(0, 0, text="Test")
e1 = Entry(canvas)
def callback():
print(e1)
def answer():
e1 = Entry(canvas)
canvas.create_window(250, 100, window=e1, height=15, width=100)
label = Label(text="Enter a word.")
label.place(x=40, y=90)
e2 = Entry(canvas)
canvas.create_window(250, 125, window=e2, height=15, width=100)
label = Label(text="Enter a word.")
label.place(x=40, y=115)
button = Button(text="Submit.", command=callback)
button.place(x=150, y=460)
answer()
canvas.pack()
mainloop()