How to center a Tkinter widget? - python

I have Tkinter window with canvas and label with 200x200 picture on it.
I want label to be in the center of the window, regardless of the window size.
from Tkinter import *
import Image, ImageTk, ImageDraw
imgsize = (200,200)
canvas_bg = "#000000"
root = Tk()
## root.geometry("350x350")
panel = PanedWindow()
panel.pack(expand=0)
canvas = Canvas(panel, bg=canvas_bg)
blank_source = Image.new('RGBA',imgsize, "#ffffff")
blank = ImageTk.PhotoImage(blank_source)
label = Label(canvas, image=blank)
label.configure(image = blank)
canvas.pack( expand=0)
mainloop()
Is there any way to do it?

Use the place geometry manager. Here is a simple example :
from tkinter import *
wd = Tk()
wd.config(height=500, width=500)
can = Canvas(wd, bg = 'red', height=100, width=100)
can.place(relx=0.5, rely=0.5, anchor=CENTER)
Basically the options work as follows:
With anchor you specify which point of the widget you are referring to and with the two others you specify the location of that point. Just for example and to get a better understanding of it, let's say you'd be sure that the window is always 500*500 and the widget 100*100, then you could also write (it's stupid to write it that way but just for the sake of explanation) :
from tkinter import *
wd = Tk()
wd.config(height=500, width=500)
can = Canvas(wd, bg = 'red', height=100, width=100)
can.place(x=200, y=200, anchor=NW)
relx and rely give a position relative to the window (from 0 to 1) : 0,4*500 = 200
x and y give absolute positions : 200
anchor=NW makes the offset options refer to the upper left corner of the widget
You can find out more over here :
http://effbot.org/tkinterbook/place.htm
And over here :
http://www.tutorialspoint.com/python/tk_place.htm

Related

How to make background Transparent in TKinter by converting Label widget into Canvas widget?

I have a code that is working perfectly but it's not giving me transparent background, (here is the image ) after a research on web, I found the solution by using canvas widget, we can us images with transparent background.
Here is my code,
import tkinter as tk
from PIL import Image, ImageTk
def work(progress=1):
if progress > 300: # define the width by yourself
return
tmp_images = ImageTk.PhotoImage(progress_images.resize((progress, 10))) # the image size
lb.image = tmp_images # keep reference
lb["image"] = tmp_images # change the image
root.add = root.after(100, work, progress+10) # define the amplitude by yourself
root = tk.Tk()
progress_images = Image.open("path.png")
lb = tk.Label(root, bg="black")
lb.pack(side="left")
work()
root.mainloop()
but I am confused how to change Label widget into Canvas ? can anyone help me please ? I am noob in Tkinter still!!!
You can use canvas.create_text(...) to replace the labels and then use canvas.itemconfig(...) to update the labels. I got this from an other stack over flow question
reference link :-
add label ..
Below is a modified code using Canvas:
import tkinter as tk
from PIL import Image, ImageTk
def work(progress=10):
if progress > 300: # define the width by yourself
return
canvas.image = ImageTk.PhotoImage(progress_images.resize((progress, 30))) # the image size
canvas.itemconfig(pbar, image=canvas.image) # update image item
root.add = root.after(100, work, progress+10) # define the amplitude by yourself
root = tk.Tk()
progress_images = Image.open("path.png")
canvas = tk.Canvas(root, width=300, height=30, bg='black', highlightthickness=0)
canvas.pack()
pbar = canvas.create_image(0, 0, anchor='nw') # create an image item
work()
root.mainloop()

Grid and Pack same time :( what can i do to use pack or grid together or is there another way [duplicate]

#import statements
from Tkinter import *
import tkMessageBox
import tkFont
from PIL import ImageTk,Image
Code to import image:
app = Tk()
app.title("Welcome")
image2 =Image.open('C:\\Users\\adminp\\Desktop\\titlepage\\front.gif')
image1 = ImageTk.PhotoImage(image2)
w = image1.width()
h = image1.height()
app.geometry('%dx%d+0+0' % (w,h))
#app.configure(background='C:\\Usfront.png')
#app.configure(background = image1)
labelText = StringVar()
labelText.set("Welcome !!!!")
#labelText.fontsize('10')
label1 = Label(app, image=image1, textvariable=labelText,
font=("Times New Roman", 24),
justify=CENTER, height=4, fg="blue")
label1.pack()
app.mainloop()
This code doesn't work. I want to import a background image.
One simple method is to use place to use an image as a background image. This is the type of thing that place is really good at doing.
For example:
background_image=tk.PhotoImage(...)
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
You can then grid or pack other widgets in the parent as normal. Just make sure you create the background label first so it has a lower stacking order.
Note: if you are doing this inside a function, make sure you keep a reference to the image, otherwise the image will be destroyed by the garbage collector when the function returns. A common technique is to add a reference as an attribute of the label object:
background_label.image = background_image
A simple tkinter code for Python 3 for setting background image .
from tkinter import *
from tkinter import messagebox
top = Tk()
C = Canvas(top, bg="blue", height=250, width=300)
filename = PhotoImage(file = "C:\\Users\\location\\imageName.png")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
C.pack()
top.mainloop
You can use this:
root.configure(background='your colour')
Example:-
import tkinter
root=tkiner.Tk()
root.configure(background='pink')

How can you have a background image with text on top on a button on tk?

I am trying to make tk buttons look better by adding a button background. The issue is, I can use an image or text, but not both, for a tk button.
How can you have both?
This is what I have tried:
from tkinter import *
from PIL import Image, ImageTk
print("I ran")
master = Tk()
canvas_width = 800
canvas_height = 400
window = Canvas(master,
width=canvas_width,
height=canvas_height)
img = Image.open("images/button_black.png").resize((80,40))
ph_image = ImageTk.PhotoImage(img)
l = Label(master, text='Button', image=ph_image, compound=CENTER, fg="white")
l.pack(side=LEFT)
button = Button ( master, image=l)
window.pack()
mainloop()
To use both an image and text you must set the compound option. From the canonical documentation:
Specifies if the widget should display text and bitmaps/images at the same time, and if so, where the bitmap/image should be placed relative to the text. Must be one of the values none, bottom, top, left, right, or center. For example, the (default) value none specifies that the bitmap or image should (if defined) be displayed instead of the text, the value left specifies that the bitmap or image should be displayed to the left of the text, and the value center specifies that the bitmap or image should be displayed on top of the text.
Example:
The following example uses this image:
The program renders like this when using compound="center":
import tkinter as tk
image_data = '''
R0lGODdhyABkAKIAAAAAAP8mAP/7AP///wAAAAAAAAAAAAAAACH5BAkAAAQALAA
AAADIAGQAAAP/KLrc/jDKSau9OOvNu/9gKI5kaZ5oqq5s675wLM90bd94ru987/
/AoHBILBqPyKRyyWw6n9CodEqtWq/YrHbL7Xq/4LB4TC6bz+i0es1uu9/wuHxOl
wTu+Lx+z+8H6jZ+goOEg4AnhYmKi3yHHIyQkZGOE5KWl5CUCpicnYx1nqGihHCj
pqd+a6irrHlnrbCwY7G0sl+1uKxeubyoXL3AplnBxMJWxciex8nMmFXN0JJU0dS
ZUtXYiVPZ3ILb3eB63+Hk4+Tg5ufc6erY0+3Zz/Du8vPQV/bRw/nFv/zAu/7lAi
Ow1qyCq14hFKVqobM3Dj/RiUhKE0U8miIUzIihNh3HEPo+toglsqTJkyhTqlzJs
qXLlzBjypxJs6bNmzhz6tzJs6fPn0CDCh1KtKjRo0iTKlWZAAA7
'''
root = tk.Tk()
image = tk.PhotoImage(data=image_data)
label = tk.Button(root, image=image, text="Hello, world", compound="center")
label.pack(padx=20, pady=20)
root.mainloop()

Tkinter/ttk frame size

I'm trying to set the frame size via theme_settings and it just doesn't work.
from Tkinter import *
from ttk import *
root = Tk()
style = Style()
style.theme_settings('default',{'TFrame':{'configure':{'width':100, 'height':100}}})
frame = Frame(root)
frame.pack()
root.mainloop()
But if I set it explicitly, then it works:
frame.configure(width=100, height=100)
Why?
ttk.version = "0.3.1"
Tkinter.version = "$Revision: 81008 $"
P.S. I need to set this size via .theme_settings() method, the question exactly about it.
UPD: I've checked the same behavior with Button element and it works. Something is wrong with frames...
style = Style()
style.theme_settings('default',{'TButton':{'configure':{'width':100}}})
button = Button(root)
button.pack()
UPD2: The same story with 'padding'. It works with buttons, but not with frames. While frames 'background' for example can be set via theme_settings
The Answer should be like that:
root = tk.Tk()
width x height + x_offset + y_offset
root.geometry("500x300+250+100")
Use the Place management as following codes:
root = tk.Tk()
root.geometry("500x300+250+100") # width x height + x_offset + y_offset

How to use an image for the background in tkinter?

#import statements
from Tkinter import *
import tkMessageBox
import tkFont
from PIL import ImageTk,Image
Code to import image:
app = Tk()
app.title("Welcome")
image2 =Image.open('C:\\Users\\adminp\\Desktop\\titlepage\\front.gif')
image1 = ImageTk.PhotoImage(image2)
w = image1.width()
h = image1.height()
app.geometry('%dx%d+0+0' % (w,h))
#app.configure(background='C:\\Usfront.png')
#app.configure(background = image1)
labelText = StringVar()
labelText.set("Welcome !!!!")
#labelText.fontsize('10')
label1 = Label(app, image=image1, textvariable=labelText,
font=("Times New Roman", 24),
justify=CENTER, height=4, fg="blue")
label1.pack()
app.mainloop()
This code doesn't work. I want to import a background image.
One simple method is to use place to use an image as a background image. This is the type of thing that place is really good at doing.
For example:
background_image=tk.PhotoImage(...)
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
You can then grid or pack other widgets in the parent as normal. Just make sure you create the background label first so it has a lower stacking order.
Note: if you are doing this inside a function, make sure you keep a reference to the image, otherwise the image will be destroyed by the garbage collector when the function returns. A common technique is to add a reference as an attribute of the label object:
background_label.image = background_image
A simple tkinter code for Python 3 for setting background image .
from tkinter import *
from tkinter import messagebox
top = Tk()
C = Canvas(top, bg="blue", height=250, width=300)
filename = PhotoImage(file = "C:\\Users\\location\\imageName.png")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
C.pack()
top.mainloop
You can use this:
root.configure(background='your colour')
Example:-
import tkinter
root=tkiner.Tk()
root.configure(background='pink')

Categories