✨✨✨
感谢优秀的你打开了小白的文章
“希望在看文章的你今天又进步了一点点,离美好生活更近一步!”🌈
place 布局管理器
place 布局管理器可以通过坐标精确控制组件的位置。
place()方法的选项
选项 | 说明 | 取值范围 |
x,y | 组件左上角的绝对坐标 (相对于窗口) | 非负整数 x 和 y 选项用于设置偏移(像素),如果同时设置 relx(rely) 和 x(y),那么 place 将优先计算 relx 和 rely,然后再实现 x 和 y 指 |
定的偏移值 | ||
relx rely | 组件左上角的坐标 (相对于父容器) | relx 是相对父组件的位置。0 是最左边,0.5 是正中间,1 是最右边; rely 是相对父组件的位置。0 是最上边,0.5 是正中间,1 是最下边; |
width, height | 组件的宽度和高度 | 非负整数 |
relwidth, relheight | 组件的宽度和高度 (相对于父容器) | 与 relx、rely 取值类似,但是相对于父组件的尺寸 |
anchor | 对齐方式,左对齐”w”, 右对齐”e”,顶对齐”n”, 底对齐”s” | “n”, “s”, “w”, “e”, “nw”, “sw”, “se”, “ne”, “center”(默认) |
简单布局管理
# coding=utf-8
from tkinter import *
root = Tk();root.geometry("500x300")
root.title("place");root["bg"]="white"
f1 = Frame(root,width=200,height=200,bg="pink")
f1.place(x=30,y=30)
Button(root,text="小白").place(relx=0.2,x=100,y=20,relwidth=0.2,relheight=0.5)
Button(f1,text="加油").place(relx=0.2,rely=0.7)
Button(f1,text="进步中").place(relx=0.3,rely=0.2)
root.mainloop()
结果:
扑克牌界面设计
from tkinter import *
class Application(Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.createWidget()
def createWidget(self):
"""通过place布局管理器实现扑克牌位置控制"""
self.photos = [PhotoImage(file="imgs/puke/puke"+str(i+1)+".gif") for i in range(10)]
self.pukes = [Label(self.master,image=self.photos[i]) for i in range(10)]
for i in range(10):
self.pukes[i].place(x=10+i*40,y=50)
self.pukes[0].bind_class("Label","<Button-1>",self.chupai)
def chupai(self,event):
print(event.widget.winfo_geometry())
print(event.widget.winfo_y())
if event.widget.winfo_y() == 50:
event.widget.place(y=30)
else:
event.widget.place(y=50)
if __name__ == '__main__':
root = Tk()
root.geometry("600x270+200+300")
app = Application(master=root)
root.mainloop()
结果展示