Python 如何将 Tkinter 小部件居中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18736465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to center a Tkinter widget?
提问by Kriattiffer
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.
我有Tkinter的窗口,canvas
并label
用200x200的图片就可以了。label
无论窗口大小如何,我都想在窗口的中央。
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?
有什么办法吗?
采纳答案by Pierre Monico
Use the place
geometry manager. Here is a simple example :
使用place
几何管理器。这是一个简单的例子:
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) :
随着anchor
你指定你指的是与另外两个小部件的这点您可以指定点的位置。举个例子,为了更好地理解它,假设你确定窗口总是 500*500,小部件总是 100*100,那么你也可以写(那样写是愚蠢的,但只是为了为了解释):
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 = 200x
and y
give absolute positions : 200anchor=NW
makes the offset options refer to the upper left corner of the widget
relx
并rely
给出相对于窗口的位置(从 0 到 1):0,4*500 = 200x
并y
给出绝对位置:200anchor=NW
使偏移选项指向小部件的左上角
You can find out more over here :
您可以在此处了解更多信息:
http://effbot.org/tkinterbook/place.htm
http://effbot.org/tkinterbook/place.htm
And over here :
在这里: