How to add background image to my application in Tkinter? - python-3.x

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

Related

I need help making a tkinter program that variably opens a picture

I'm trying to make a program that has a button that will open a picture if a variable is in a certain state, and change how the button looks (or maybe show a different picture) if it's not. I have been trying to work through the bugs I've been getting.
This is honestly intermediary code so I can understand how to make what I'm actually trying to do, make a network-enabled GUI for some physical buttons.
I've tried passing blueButton in as a variable, but that didn't work.
import tkinter as tk
weather = "sunny"
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.blueButton = tk.Button(self, fg = "blue")
self.blueButton["text"] = "I'm Blue"
self.blueButton["command"] = self.change
self.blueButton.pack(anchor="nw")
self.quit = tk.Button(self, text = "QUIT", fg = "red",
command = self.master.destroy)
self.quit.pack(side="bottom")
self.pack(fill = "both", expand = 1)
def change(self):
global weather
if weather == "sunny":
w = tk.Canvas(root, width=400, height=750)
img = tk.PhotoImage(file = "haunter.gif")
w.create_image((200, 200), image = img)
w.pack()
else:
self.blueButton["bitmap"] = "error"
root = tk.Tk()
root.geometry("400x300")
app = Application(master = root)
app.mainloop()
The canvas gets made, but the picture doesn't show up, the "quit" button just moves.
I've also gotten the error "name blueButton is not defined".
You could keep the image as an attribute of your App, put it on a canvas, then show or hide the canvas depending on the weather.
import random
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.blueButton = tk.Button(self, fg = "blue")
self.blueButton["text"] = "I'm Blue"
self.blueButton["command"] = self.change
self.blueButton.pack()
self.quit = tk.Button(self, text = "QUIT", fg = "red",
command = self.master.destroy)
self.quit.pack()
self.pack(fill = "both", expand = 1)
self.canvas = tk.Canvas(root, width=400, height=750)
# self.sunny_img = tk.PhotoImage(file="haunter.gif")
self.sunny_img = tk.PhotoImage(file="rapporteur.gif")
self.canvas.create_image((200, 200), image=self.sunny_img)
def change(self):
weather = ['sunny', 'rainy']
current_weather = random.choice(weather)
if current_weather == 'sunny':
self.canvas.pack()
self.blueButton["bitmap"] = ''
else:
self.canvas.pack_forget()
self.blueButton["bitmap"] = "error"
root = tk.Tk()
root.geometry("400x300")
app = Application(master = root)
app.mainloop()

Tkinter - Canvas in new window and the image resize to the new window resolution

I'm trying to do a Canvas that display a picture in a new window with a pressing a button, actually that is working, but I need the display that show the image in the new windows resize to the new window dimension.
I already tried to manage to get the size to an specific but nothing really worked out for me.
Here is the code:
from tkinter import *
import requests
import shutil
from xml.dom.minidom import parse
import fileinput
import os.path as path
import os
import tempfile
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.master = master
root = Tk()
root.title("Etiquetas")
root.configure(width=1280,height=720)
root.geometry('{}x{}'.format(427, 600))
root.resizable(width=False, height=False)
canvas = Canvas(root, width=500, height=500)
canvas.pack(fill="both", expand=True)
my_image = PhotoImage(file='label.png')
def new_winF(): # new window definition
newwin = Toplevel(root)
display = Label(newwin, text="Humm, see a new window !")
display.pack()
def retrieve_input():
f = open('DataXML.xml', 'w+')
f.truncate(0)
inputParamString = ParamString.get("1.0","end-1c")
inputAlto = Alto.get("1.0","end-1c")
inputAncho = Ancho.get("1.0","end-1c")
inputTemplateLabel = TemplateLabel.get("1.0","end-1c")
#StringEtiqueta = open("DataXML.xml", "a+")
f.write(inputParamString)
f.close()
doc = parse("DataXML.xml")
my_node_list = doc.getElementsByTagName("label_param")
LabelResultado = open("Template.txt", "w")
LabelResultado.write(inputTemplateLabel)
LabelResultado.close()
for node in my_node_list:
name_node = node.getElementsByTagName("name")
value_node = node.getElementsByTagName("value")
y = ("[" + name_node[0].firstChild.data + "]")
z = y.upper()
print(z)
if (value_node[0].firstChild != None):
print(value_node[0].firstChild.data)
x = value_node[0].firstChild.data
else:
print("")
x = ""
with fileinput.FileInput("Template.txt", inplace=True) as file:
for line in file:
print(line.replace(z, x), end='')
w = open('Template.txt.bak', 'w+')
w.close()
codigoZPL = open("Template.txt", "r")
zpl = codigoZPL.read()
codigoZPL.close()
url = ('http://api.labelary.com/v1/printers/8dpmm/labels/'+inputAlto+'x'+inputAncho+'/0/')
files = {'file': zpl}
#headers = {'Accept': 'application/pdf'}
response = requests.post(url, headers=0, files=files, stream=True)
if response.status_code == 200:
response.raw.decode_content = True
with open('label.png', 'wb') as out_file: # change file name for PNG images
shutil.copyfileobj(response.raw, out_file)
else:
print('Error: ' + response.text)
newwin = Toplevel(root)
ncanvas = Canvas(newwin, width=500, height=500)
canvas.pack(fill="both", expand=True)
my_image = PhotoImage(file='label.png')
display = canvas.create_image(850, 50, anchor=NE, image=my_image)
line = canvas.create_line(0, 0, 0, 0)
display.pack()
root.mainloop()
def click_limpiar():
Alto.delete(0.0, END)
Ancho.delete(0.0, END)
ParamString.delete(0.0, END)
TemplateLabel.delete(0.0, END)
def close_window():
root.destroy()
exit()
#Crear un label
Label (text="Ingresar ParamString: ") .place(x=10,y=15)
Label (text="Ingresar TamaƱo (pulgadas): ") .place(x=10,y=160)
Label (text="Ingresar TemplateLabel: ") .place(x=10,y=218)
#Crear un textbox
ParamString = Text(root)
ParamString.pack()
ParamString.place(x=12, y=50, height=100, width=400)
Alto = Text(root)
Alto.pack()
Alto.place(x=12, y=190, height=20, width=20)
Ancho = Text(root)
Ancho.pack()
Ancho.place(x=52, y=190, height=20, width=20)
TemplateLabel = Text(root)
TemplateLabel.pack
TemplateLabel.place(x=12, y=250, height=300, width=400)
#Botones
Button(root, text="Aceptar", width=16, command=retrieve_input) .place(x=20,y=560)
Button(root, text="Limpiar", width=16, command=click_limpiar) .place(x=150,y=560)
Button(root, text="Salir", width=16, command=close_window) .place(x=280,y=560)
app = Window(root)
root.mainloop()
The Canvas part is this one:
newwin = Toplevel(root)
ncanvas = Canvas(newwin, width=500, height=500)
canvas.pack(fill="both", expand=True)
my_image = PhotoImage(file='label.png')
display = canvas.create_image(850, 50, anchor=NE, image=my_image)
line = canvas.create_line(0, 0, 0, 0)
display.pack()
Thanks in advance,

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 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.

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