How to add buttons and labels on frame if its resizable - python

i have a code:
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
root.geometry("900x580")
class Example(Frame):
def __init__(self, master, *pargs):
Frame.__init__(self, master, *pargs)
self.image = Image.open("eth_background.png")
self.img_copy= self.image.copy()
self.background_image = ImageTk.PhotoImage(self.image)
self.background = Label(self, image=self.background_image)
self.background.pack(fill=BOTH, expand=YES)
self.background.bind('<Configure>', self._resize_image)
self.widget = Button(self, text='Hello world', command=self.quit)
self.widget.pack(side=LEFT)
def _resize_image(self,event):
new_width = event.width
new_height = event.height
self.image = self.img_copy.resize((new_width, new_height))
self.background_image = ImageTk.PhotoImage(self.image)
self.background.configure(image = self.background_image)
e = Example(root)
e.pack(fill=BOTH, expand=YES)
root.mainloop()
I did that bacground is automaticly resize, but now i cant add buttons or lables on a frame. I found it:
from Tkinter import *
class Hello(Frame):
def __init__(self, parent=None):
Frame.__init__(self, parent)
self.pack()
self.make_widgets()
def make_widgets(self):
widget = Button(self, text='Hello world', command=self.quit)
widget.pack(side=LEFT)
if __name__ == '__main__': Hello().mainloop()
but it obviously doesnt work, how i can do that frame, resizable bacground, and buttons on it?

Related

python tkinter resize background image according to window size

The background image is not adjusting automatically to the window size in python using tkinter
Following is the code snippet
self.background_image = tk.PhotoImage(file="background.png")
self.background_label = tk.Label(self.master, image=self.background_image)
self.background_label.pack(fill='both', expand=True)
The image should be in background of the behind all the GUI components.
The code is actually a part of a python GUI but the image is not resizing automatically according to the window size previously i tried this but it was to add a static image but in need the image to fit automatically to the window size
This is the kinda the complete code
import tkinter as tk
from tkinter import ttk
class MongoDBGUI:
def __init__(self, master):
self.master = master
self.master.title("MongoDB Cloud Search and Display")
self.master.geometry("1000x400")
self.background_image = tk.PhotoImage(file="background.png")
self.background_label = tk.Label(self.master, image=self.background_image)
self.background_label.place(relwidth=1, relheight=1)
self.label = tk.Label(self.master, text="Enter search criteria:")
self.label.pack()
self.entry = tk.Entry(self.master)
self.entry.pack()
self.search_button = tk.Button(self.master, text="Search", command=self.search)
self.search_button.pack()
self.tree = ttk.Treeview(self.master)
self.tree.pack()
self.tree["columns"] = ("transcript", "audio_file", "audio")
self.tree.column("transcript", width=400, anchor="center")
self.tree.column("audio_file", width=150, anchor="center")
self.tree.column("audio", width=50, anchor="center")
self.tree.heading("transcript", text="Transcript")
self.tree.heading("audio_file", text="Audio File Number")
self.tree.heading("audio", text="Audio")
This is an not so easy task. If you want to have a resizable image then you need to use the PIL package. Additionally a further method is needed to rezise the image dynamically. Ofcourse if the window size always stays the same the solution could be implemented like :
self.image = self.img_copy.resize((new_width, new_height))
#resize is included in the PIL.Image module
To dynamically resize the background Picture the code could look like this:
import tkinter as tk
from tkinter import ttk
from scipy import misc,datasets
from PIL import Image, ImageTk
class MongoDBGUI:
def __init__(self, master):
self.master = master
self.master.title("MongoDB Cloud Search and Display")
self.master.geometry("1000x400")
self.image = Image.open("background.png")
self.background_image = ImageTk.PhotoImage(self.image)
self.img_copy = self.image.copy()
self.background_label = tk.Label(self.master, image=self.background_image)
self.background_label.place(relwidth=1, relheight=1)
self.label = tk.Label(self.master, text="Enter search criteria:")
self.label.pack()
self.entry = tk.Entry(self.master)
self.entry.pack()
self.search_button = tk.Button(self.master, text="Search", command=self.search)
self.search_button.pack()
self.tree = ttk.Treeview(self.master)
self.tree.pack()
self.tree["columns"] = ("transcript", "audio_file", "audio")
self.tree.column("transcript", width=400, anchor="center")
self.tree.column("audio_file", width=150, anchor="center")
self.tree.column("audio", width=50, anchor="center")
self.tree.heading("transcript", text="Transcript")
self.tree.heading("audio_file", text="Audio File Number")
self.tree.heading("audio", text="Audio")
self.background_label.bind('<Configure>', self._resize_image)
def _resize_image(self,event):
new_width = event.width
new_height = event.height
self.image = self.img_copy.resize((new_width, new_height))
self.background_image = ImageTk.PhotoImage(self.image)
self.background_label.configure(image = self.background_image)
master=tk.Tk()
test=MongoDBGUI(master)
master.mainloop()

TKinter background resizer + buttons/labels

I'm trying to setup tkinter gui screen with wallpaper on the background when the bg image fit the resize of the screen, i have took code from here..but the problem is when i'm trying to put buttons on it or another labels, the wallpaper still stay on the top and i can't see them.
Here the code:
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
root.title("Title")
root.geometry("800x600")
class Example(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.configure(background="black")
self.grid(sticky=N+S+E+W)
self.image = Image.open("bg.jpg")
self.img_copy= self.image.copy()
self.background_image = ImageTk.PhotoImage(self.image)
self.background = Label(self, image=self.background_image)
self.background.grid(row =0, column =0,sticky="nsew")
self.background.grid_rowconfigure(0, weight=1)
self.background.grid_columnconfigure(0, weight=1)
self.master = master
self.master.bind('<Configure>', self._resize_image)
# create a button
self.button= Button(root, text="EXIT", width=4).grid(row=3, column=1, sticky=N+S+E+W)
def _resize_image(self,event):
new_width = self.master.winfo_width()
new_height = self.master.winfo_height()
self.image = self.img_copy.resize((new_width, new_height))
self.background_image = ImageTk.PhotoImage(self.image)
self.background.configure(image = self.background_image)
e = Example(root)
e.grid(row =0, column =0,sticky="nsew")
e.grid_rowconfigure(0, weight=1)
e.grid_columnconfigure(0, weight=1)
root.mainloop()
You need to use place() to put the background image so that it does not interfere other widgets in the same parent.
Below is a simplified example based on your code:
from tkinter import *
from PIL import Image, ImageTk
class Example(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.configure(background="black")
self.image = Image.open("bg.jpg")
# label for the background image
self.background = Label(self)
self.background.place(x=0, y=0)
self.bind('<Configure>', self._resize_image)
# create a button
self.button = Button(self, text="EXIT", width=4)
self.button.grid(row=3, column=1, sticky=N+S+E+W, padx=50, pady=50)
def _resize_image(self,event):
if event.widget is self:
# resize background image to fit the frame size
image = self.image.resize((event.width, event.height))
self.background_image = ImageTk.PhotoImage(image)
self.background.configure(image=self.background_image)
root = Tk()
root.title("Title")
root.geometry("800x600")
e = Example(root)
e.pack(fill=BOTH, expand=1)
root.mainloop()

Unable fetch text variable data in class in tkinter

I am trying to fetch the data from text variable and image in a function name loopCap and display it in __init__ function where I have created a canvas but due to mentioned below error I am not able to move further
For text Error:
*(args + self._options(cnf, kw))))
_tkinter.TclError: unknown option "-textvariable"
For Image Error:
self.put_photo = canvas.create_image(70, 250, image=self.photo, anchor='nw')
AttributeError: 'StartPage' object has no attribute 'photo'
Actual Code Sample:
import tkinter as tk
from tkinter import *
from tkinter.filedialog import asksaveasfile
from tkinter import messagebox
from PIL import ImageTk, Image
im = "BG.jpg"
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.ard_stat = read_json(JSON_PATH)
self.switch_frame(StartPage)
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
class StartPage(tk.Frame):
def loopCap(self):
with open(JSON_PATH) as json_file1:
self.data = json.load(json_file1)
print(self.data)
if self.data['status'] == 'ACTIVE': # and (self.data['RH_img']!= 'null' or self.data['LH_img']!= 'null')
a = self.text.set(self.data['status'])
if self.data['RH_img'] == 'NA':
self.img = Image.open(Press)
self.img.load()
self.photo = ImageTk.PhotoImage(self.img)
self.label['image'] = self.photo
self.master.after(500, self.loopCap)
def __init__(self, master):
super().__init__(master)
self.master.config(bg='black')
Frame2 = tk.Frame(self.master)
Frame2.pack(fill='both',expand = True)
self.photo_back = ImageTk.PhotoImage(im)
lab_1 = tk.Label(Frame2, image=self.photo_back)
lab_1.image = self.photo_back
lab_1.place(x=0, y=0, relwidth=1, relheight=1)
canvas = Canvas(Frame2, width=1000, height=700)
canvas.place(x=0, y=0, relwidth=1, relheight=1)
canvas.create_image(0, 0, image=self.photo_back, anchor='nw')
self.text = tk.StringVar()
canvas.create_text(230, 170, fill="white", font="Times 20 bold",
textvariable=self.text, anchor="w")
self.label = tk.Label(canvas)
self.put_photo = canvas.create_image(70, 250, image=self.photo, anchor='nw')
canvas.itemconfig(self.put_photo, image=self.photo)
self.master.after(500, self.loopCap)
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
Any suggestions will be a great help.
Try replacing "textvariable=" with "text="
canvas.create_text(230, 170, fill="white", font="Times 20 bold", text=self.text, anchor="w")

How do I make the background in a tkinter window transparent?

How do I make this so the window background is transparent, but the image remains visible?
Here is my code;
from tkinter import Tk, Label, Button, Canvas
from PIL import ImageTk, Image
class MyFirstGUI:
def __init__(self, master):
self.canvas = Canvas(master, width = 300, height = 300)
self.canvas.pack()
self.image = ImageTk.PhotoImage(Image.open("Sprites/ph1.png"))
self.canvas.create_image(150, 150, image=self.image)
self.master = master
master.title("A simple GUI")
self.close_button = Button(master, text="Close", command=master.quit)
self.close_button.pack()
def greet(self):
print("Greetings!")
root = Tk()
root.geometry("+1630+775")
root.overrideredirect(1)
my_gui = MyFirstGUI(root)
root.mainloop()

Filling frame with color

I'm trying to fill the frame with the buttons so it extends the background-color to the end of the window both sides, this worked when doing .pack() but not .grid().
My code:
from tkinter import *
class App:
def __init__(self):
self.root = Tk()
self.width = 800
self.height = 400
self.root.geometry("{}x{}".format(self.width, self.height))
self.root.resizable(False, False)
self.menu_bar()
self.tool_bar()
self.name = Label(self.root, text="Tester", bg="black", fg="white")
self.root.mainloop()
def menu_bar(self):
self.menu = Menu(self.root)
self.root.config(menu=self.menu)
self.subMenu = Menu(self.menu)
self.menu.add_cascade(label="File", menu=self.subMenu)
self.subMenu.add_command(label="New Project...")
self.subMenu.add_command(label="Properties")
self.subMenu.add_separator()
self.subMenu.add_command(label="Do nothing")
def tool_bar(self):
self.toolbar = Frame(self.root, bg="#555555")
self.insert_button = Button(self.toolbar, text="Insert", bg="#555555", fg="white", activeforeground="white",
activebackground="#008CBA", borderwidth=0)
self.insert_button.grid(row=0, column=0)
self.print_buttom = Button(self.toolbar, text="Print", bg="#555555", fg="white", activeforeground="white",
activebackground="#008CBA", borderwidth=0,
command=self.root.quit)
self.print_buttom.grid(row=0, column=1)
self.toolbar.grid(row=0, column=0, sticky=EW)
if __name__ == '__main__':
App()
Thanks for answers in advance.
You can set a weight to your column.
class App:
def __init__(self):
self.root = Tk()
...
self.root.columnconfigure(0,weight=1)
...

Categories