Why the image didn't come out in python? - python

I try to add image in tkinter but it didn't show up but when I added label of text,the text show but the image didn't.Thank you
from tkinter import *
class window1:
def __init__(self, parent, word, geometry):
# image
bank_img = PhotoImage(file='C:\\Users\\user\\PycharmProjects\\pythonProject3\\bank-988164_640.png')
self.parent = parent
self.word = word
self.geometry = geometry
parent.geometry(geometry)
parent.title(self.word)
# Label
label = Label(parent, text="Welcome to the bank", height=3).pack()
bank_logo = Label(parent,image=bank_img).pack()
root = Tk()
app = window1(root, 'beginner bank system', '300x300')

Add root.mainloop() at the end.
root = Tk()
app = window1(root, 'beginner bank system', '300x300')
root.mainloop()

Related

Tkinter Widget Placement

I'm currently trying to create a desktop file converter application for myself using tkinter. It so far has a drag and drop area, and a button you can press to just select the file from the file explorer. However, I'm having trouble figuring out how to correctly position the widgets so they sit on top of each other. I want it so the drag and drop box is off the the left side of the screen, and in the middle of the box I want a text widget that says, "Drag and drop file, or select them", with a button widget below it that allows them to select from the file manager if they please.
import tkinter as tk
import tkinter.filedialog
from TkinterDnD2 import DND_FILES, TkinterDnD
from conversion import *
#global variables
path_to_file = " "
file_type = " "
compatable_converstion = []
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.master.title("File Converter")
self.master.minsize(1000,600)
self.master.maxsize(1200,800)
self.pack()
self.create_widgets()
def create_widgets(self):
#Drag and drop files area
self.drop_box = tk.Listbox(root, selectmode=tk.SINGLE, background="#99ff99")
self.drop_box.pack(ipadx=170)
self.drop_box.pack(ipady=120)
self.drop_box.pack(side="left")
self.drop_box.drop_target_register(DND_FILES)
self.drop_box.dnd_bind("<<Drop>>", open_dropped_file)
#Select file button
self.select_file = tk.Button(self)
self.select_file["text"] = "Select File"
self.select_file["command"] = self.open_selected_file
self.select_file.place(relx=1.0, rely=1.0, anchor="se")
#Instructional Text
sentence = "Drag and drop or select your file"
self.instructions = tk.Text(root)
self.instructions.insert(tk.END, sentence)
self.instructions.place(relx=1.0, rely=1.0, anchor="se")
def open_selected_file(self):
path_to_file = tk.filedialog.askopenfilename(initialdir="/", title="Select A File", filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
temp_str = " "
for chars in reversed(path_to_file):
if(chars == '.'):
break
temp_str += chars
file_type = temp_str[::-1]
compatable_converstion = retrieve_compatable_conversions(file_type)
def main():
global root
root = TkinterDnD.Tk()
app = Application(master=root)
app.mainloop()
if __name__ == "__main__":
main()
Just in case my explanation of how I want it laid out sucks, here is a picture:
You are creating the widgets self.drop_box and self.instructions on the root window. They should be created on self.
The place() geometry manager does not reserve space in a widget, so you will have to make the widget(self) as big as necessary with expand=True, fill='both'. I would advise using the grid() geometry manager for any design which is not really simple.
The widgets will be stacked in the order they are placed, which means that the Button will be hidden beneath the Text widget. Just change the order in which they are placed.
As for using ipadx and ipady in the pack() function, have a look at Why does the 'ipady' option in the tkinter.grid() method only add space below a widget?
Also; you don't need to make root a global variable because the application knows it as self.master.
Here is an example, not of the whole program but the parts I have mentioned:
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.master.title("File Converter")
self.master.minsize(1000,600)
self.master.maxsize(1200,800)
self.pack(expand=True, fill='both') # Fill entire root window
self.create_widgets()
def create_widgets(self):
#Drag and drop files area
self.drop_box = tk.Listbox(self, selectmode=tk.SINGLE, background="#99ff99")
self.drop_box.pack(side="left", ipadx=170, ipady=120)
self.drop_box.drop_target_register(DND_FILES)
self.drop_box.dnd_bind("<<Drop>>", open_dropped_file)
#Instructional Text
sentence = "Drag and drop or select your file"
self.instructions = tk.Text(self)
self.instructions.insert(tk.END, sentence)
self.instructions.place(relx=1.0, rely=1.0, anchor="se")
#Select file button
self.select_file = tk.Button(self, text="Select File",
command=self.open_selected_file)
self.select_file.place(relx=1.0, rely=1.0, anchor="se")
This should let you work out most of your problems.

How to display image with upload button in and resize it with window resize (Dynamically)with Tkinter python, I need to add upload button

I need to add upload button so that I can upload the picture and display with this class. Everything working but when I am adding the upload button its giving me some error and my code is not wokring.
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
from tkinter import filedialog
class Layout:
def __init__(self,master):
self.master = master
self.rootgeometry()
self.canvas = tk.Canvas(self.master)
self.canvas.pack()
self.background_image = Image.open(self.openfn())
self.image_copy = self.background_image.copy()
self.background = ImageTk.PhotoImage(self.background_image)
self.loadbackground()
def loadbackground(self):
self.label = tk.Label(self.canvas, image = self.background)
self.label.bind('<Configure>',self.resizeimage)
self.label.pack(fill='both', expand='yes')
def openfn(self):
filename = filedialog.askopenfilename(title='open')
return filename
def rootgeometry(self):
x=int(self.master.winfo_screenwidth()*0.7)
y=int(self.master.winfo_screenheight()*0.7)
z = str(x) +'x'+str(y)
self.master.geometry(z)
def resizeimage(self,event):
image = self.image_copy.resize((self.master.winfo_width(),self.master.winfo_height()))
self.image1 = ImageTk.PhotoImage(image)
self.label.config(image = self.image1)
root = tk.Tk()
a = Layout(root)
root.mainloop()
Create the Button widget within the class constructor and bind it with self.loadbackground. Also, you don't need to recreate the Label widget every time instead use label.configure(image=yourimage).
Here is the code:
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
from tkinter import filedialog
class Layout:
def __init__(self,master):
self.master = master
self.rootgeometry()
self.button = Button(self.master, text='Upload', command=self.loadbackground)
self.button.pack()
self.canvas = tk.Canvas(self.master)
self.canvas.pack(fill=BOTH, expand=True)
self.background_image = None
self.image_copy = None
self.background = None
self.label = tk.Label(self.canvas)
self.label.pack(fill='both', expand=True)
def loadbackground(self):
self.background_image = Image.open(self.openfn())
self.image_copy = self.background_image.copy()
self.background = ImageTk.PhotoImage(self.background_image.resize((self.canvas.winfo_width(), self.canvas.winfo_height())))
self.label.configure(image=self.background)
self.label.bind('<Configure>',self.resizeimage)
def openfn(self):
filename = filedialog.askopenfilename(title='open')
return filename
def rootgeometry(self):
x=int(self.master.winfo_screenwidth()*0.7)
y=int(self.master.winfo_screenheight()*0.7)
z = str(x) +'x'+str(y)
self.master.geometry(z)
def resizeimage(self,event):
image = self.image_copy.resize((event.width, event.height))
self.image1 = ImageTk.PhotoImage(image)
self.label.config(image = self.image1)
root = tk.Tk()
a = Layout(root)
root.mainloop()

How to add a hyperlink to a tkinter button

I currently working on some code on Tkinter and I want to know if its possibly and if so how to add a website hyperlink to a button. In my case I'm trying to add the Caldicot School web address to a button through Tkinter on Python 3 and when its clicked it sends you there
Welcome to SO!
This page has a recipe for creating a button that acts like a hyperlink in tkinter
http://code.activestate.com/recipes/580774-tkinter-link-or-hyperlink-button/
The main part of the code is as follows:
if __name__ == "__main__":
import webbrowser
try:
from Tkinter import Tk, Frame
except ImportError:
from tkinter import Tk, Frame
def callback():
webbrowser.open_new(r"http://www.google.com")
root = Tk()
frame = Frame(root, bg="white")
frame.pack(expand=True, fill="both")
# Creates a button that, when clicked, calls the function that sends you to your hyperlink.
link = Link_Button(frame, text="Google Hyperlink", action=callback)
link.pack(padx=10, pady=10)
root.mainloop()
Check the website above for the code behind the class Link_Button. In case the link dies, here's the rest of the code:
# Author: Miguel Martinez Lopez
try:
from Tkinter import Label
from ttk import Style
from tkFont import Font, nametofont
except ImportError:
from tkinter import Label
from tkinter.ttk import Style
from tkinter.font import Font, nametofont
def get_background_of_widget(widget):
try:
# We assume first tk widget
background = widget.cget("background")
except:
# Otherwise this is a ttk widget
style = widget.cget("style")
if style == "":
# if there is not style configuration option, default style is the same than widget class
style = widget.winfo_class()
background = Style().lookup(style, 'background')
return background
class Link_Button(Label, object):
def __init__(self, master, text, background=None, font=None, familiy=None, size=None, underline=True, visited_fg = "#551A8B", normal_fg = "#0000EE", visited=False, action=None):
self._visited_fg = visited_fg
self._normal_fg = normal_fg
if visited:
fg = self._visited_fg
else:
fg = self._normal_fg
if font is None:
default_font = nametofont("TkDefaultFont")
family = default_font.cget("family")
if size is None:
size = default_font.cget("size")
font = Font(family=family, size=size, underline=underline)
Label.__init__(self, master, text=text, fg=fg, cursor="hand2", font=font)
if background is None:
background = get_background_of_widget(master)
self.configure(background=background)
self._visited = visited
self._action = action
self.bind("<Button-1>", self._on_click)
#property
def visited(self):
return self._visited
#visited.setter
def visited(self, is_visited):
if is_visited:
self.configure(fg=self._visited_fg)
self._visited = True
else:
self.configure(fg=self._normal_fg)
self._visited = False
def _on_click(self, event):
if not self._visited:
self.configure(fg=self._visited_fg)
self._visited = True
if self._action:
self._action()
You can basicly add this method:
from tkinter import *
from tkinter import ttk
import webbrowser
root = Tk()
root.title = 'Link Button'
def link():
webbrowser.open_new(r"https://www.python.org")
and then link method to the button:
nut = ttk.Button(root, text='Link Button', command=link)
nut.pack()
root.mainloop()
import tkinter
import webbrowser
root = Tk()
root.title = 'link to the button'
def link():
webbrowser.open_new(r"https://www.python.org")
nut = ttk.Button(root, text='link to the button')
nut.pack()
root.mainloop()
and then just simply use
nut = ttk.Button(root, text= 'link to the button', command=link)
nut.pack()
root.mainloop()

Tkinter - Open one window and close another

I want to have a login screen and when the login is successful, the screen is closed and a new screen is created. The problem is , when I do just like the following code , both screens opens at the same time. If you have any suggestions to improve the code , please do! :)
from Tkinter import *
import mysql.connector
import tkMessageBox
class Tela_login(Frame):
root = Tk()
root.geometry("1024x768")
root.resizable(width=FALSE, height=FALSE)
background_image = PhotoImage(file="fundo.gif")
def __init__(self,master):
Frame.__init__(self,master)
self.grid()
fundo = Label(image=self.background_image)
fundo.place(x=0,y=0,relwidth=1,relheight=1)
self.create_screen()
def create_screen(self):
self.label1 = Label(text="Login",font = ("Arial",60))
self.label2 = Label(text="Senha",font = ("Arial",60))
self.login = Entry(font = ("Arial",60),width = 10)
self.senha = Entry(show="*",font = ("Arial",60), width= 10)
self.entrar = Button(text="Entrar",command=lambda : self.efetua_login(),font = ("Arial",60),width=10)
self.label1.grid(padx=258,pady=(70,0))
self.login.grid(padx=258)
self.label2.grid(padx=258,pady=(50,0))
self.senha.grid(padx=258)
self.entrar.grid(padx=258,pady=(50,0))
def efetua_login(self):
login = self.login.get()
senha = self.senha.get()
cnx = mysql.connector.connect(user='root', password='123qwe', host='192.168.56.1', database='teste')
cursor = cnx
cursor = cnx.cursor()
query = ("SELECT nome, senha FROM funcionario WHERE nome = %s AND senha = %s")
cursor.execute(query, (login,senha))
row = cursor.fetchone()
if row is None:
tkMessageBox.showinfo("Erro","Usuario ou Senha Incorretos")
else:
app2 = Tela_principal()
self.root.destroy()
Tela_principal.root.mainloop()
class Tela_principal(Frame):
root = Tk()
root.geometry = ("1024x768")
root.resizable(width=FALSE, height=FALSE)
def inicia(self, master):
background_image = PhotoImage(file="fundo.gif")
app2 = Tela_principal(self.root)
Frame.__init__(self, master)
self.grid()
self.create_widgets()
app = Tela_login(Tela_login.root)
Tela_login.root.mainloop()
You probably don't want to have two Tk() instances running. For the login screen there's two routes you could go. You could withdraw the root window and make the login screen a Toplevel withdrawing the root window upon the Toplevel's initialization window and once the login is successful destroy the toplevel and raise the root window. Or, even easier you could put your login screen in a separate frame, hide the main frame using pack_forget or grid_forget depending on your layout and then login / destroy or hide the frame and recall pack or grid to show the main app frame again.
Slayer , I did like you said and it worked like a charm!
Here is the example code:
from tkinter import *
class Tela_login(Frame):
def __init__(self,master):
Frame.__init__(self, master)
self.grid()
self.button1 = Button(text = "Open",command = lambda: self.open_login())
self.button1.grid()
def open_login(self):
root2 = Toplevel()
app2 = Tela_principal(root2)
class Tela_principal(Frame):
def __init__(self,master):
Frame.__init__(self, master)
self.grid
root = Tk()
root.geometry("800x600")
app = Tela_login(root)
root.mainloop()

How to update image in tkinter label?

I'm a beginner in python so this may be too simple question to ask but i need help..With this code i cannot update image in tkinter label. I can even resize window according to new loaded image's attributes but the new image is not displayed in tkinter label.
from Tkinter import Frame, Tk, Label, Text, Menu, END, BOTH, StringVar
from PIL import ImageTk, Image
import numpy
import tkFileDialog
class DIP(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("DIP Algorithms- Simple Photo Editor")
self.pack(fill=BOTH, expand=1)
menubar = Menu(self.parent)
self.parent.config(menu=menubar)
#Open Image Menu
fileMenu = Menu(menubar)
fileMenu.add_command(label="Open", command=self.onOpen)
menubar.add_cascade(label="File", menu=fileMenu)
#menu for image ngative
basicMenu=Menu(menubar)
basicMenu.add_command(label="Negative", command=self.onNeg)
menubar.add_cascade(label="Basic", menu=basicMenu)
#Image Negative Menu callback
def onNeg(self):
I2=255-self.I;
im = Image.fromarray(numpy.uint8(I2))
photo2=ImageTk.PhotoImage(im)
self.label2= Label(self.parent,border=25,image=photo2)
self.label2.image = photo2 # keep a reference!
self.label2.grid(row=1, column=2)
def setImage(self):
self.img=Image.open(self.fn)
self.I = numpy.asarray(self.img)
l,h = self.img.size
text=str(2*l+100)+"x"+str(h+50)+"+0+0"
self.parent.geometry(text)
photo = ImageTk.PhotoImage(self.img)
self.label1 = Label(self.parent,border=25,image=photo)
self.label1.configure(image=photo)
self.label1.image = photo # keep a reference!
self.label1.grid(row=1, column=1)
#Open Callback
def onOpen(self):
ftypes = [('Image Files', '*.tif *.jpg *.png')]
dlg = tkFileDialog.Open(self, filetypes = ftypes)
filename = dlg.show()
self.fn=filename
#print self.fn #prints filename with path here
self.setImage()
#def onError(self):
#box.showerror("Error", "Could not open file")
def main():
root = Tk()
DIP(root)
root.geometry("320x240")
root.mainloop()
if __name__ == '__main__':
main()
When i run this code, and open an image , it is displayed in label1. But when i open another image again, i' expecting it to be displayed in same label1, but it's not happening. I know the 2nd image is loaded because the window size resized accordingly, the only problem is that it's not being displayed and i cannot figure out why!.
Instead of creating an new tk.Label each time setImage is called, just create it once outside of setImage -- for example, in initUI.
You can then change the image by calling self.label.configure:
import Tkinter as tk
import Image
import ImageTk
import numpy as np
import tkFileDialog
class DIP(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("DIP Algorithms- Simple Photo Editor")
self.pack(fill = tk.BOTH, expand = 1)
menubar = tk.Menu(self.parent)
self.parent.config(menu = menubar)
self.label1 = tk.Label(self, border = 25)
self.label2 = tk.Label(self, border = 25)
self.label1.grid(row = 1, column = 1)
self.label2.grid(row = 1, column = 2)
#Open Image Menu
fileMenu = tk.Menu(menubar)
fileMenu.add_command(label = "Open", command = self.onOpen)
menubar.add_cascade(label = "File", menu = fileMenu)
#menu for image ngative
basicMenu = tk.Menu(menubar)
basicMenu.add_command(label = "Negative", command = self.onNeg)
menubar.add_cascade(label = "Basic", menu = basicMenu)
def onNeg(self):
#Image Negative Menu callback
I2 = 255-self.I;
im = Image.fromarray(np.uint8(I2))
photo2 = ImageTk.PhotoImage(im)
self.label2.image = photo2 # keep a reference!
def setImage(self):
self.img = Image.open(self.fn)
self.I = np.asarray(self.img)
l, h = self.img.size
text = str(2*l+100)+"x"+str(h+50)+"+0+0"
self.parent.geometry(text)
photo = ImageTk.PhotoImage(self.img)
self.label1.configure(image = photo)
self.label1.image = photo # keep a reference!
def onOpen(self):
#Open Callback
ftypes = [('Image Files', '*.tif *.jpg *.png')]
dlg = tkFileDialog.Open(self, filetypes = ftypes)
filename = dlg.show()
self.fn = filename
#print self.fn #prints filename with path here
self.setImage()
#def onError(self):
#box.showerror("Error", "Could not open file")
def main():
root = tk.Tk()
DIP(root)
root.geometry("320x240")
root.mainloop()
if __name__ == '__main__':
main()

Categories

Resources