如何将 Tkinter 小部件居中? [英] How to center a Tkinter widget?
问题描述
我有带有 canvas
和 label
的 Tkinter 窗口,上面有 200x200 图片.无论窗口大小如何,我都希望 label
位于窗口的中心.
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()
有什么办法吗?
推荐答案
使用 place
几何管理器.这是一个简单的例子:
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:
使用 anchor
指定您所指的小部件的哪个点,并使用其他两个指定该点的位置.举个例子,为了更好地理解它,假设你确定窗口总是 500*500,小部件总是 100*100,那么你也可以写(那样写是愚蠢的,但只是为了为了解释):
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
和 rely
给出相对于窗口的位置(从 0 到 1):0,4*500 = 200x
和 y
给出绝对位置:200anchor=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
这里:
http://www.tutorialspoint.com/python/tk_place.htm
这篇关于如何将 Tkinter 小部件居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!