tkinter——部件布局和摆放

本文介绍了Tkinter中的三种布局管理器:pack(), grid() 和 place() 的使用方法及示例代码。通过实例展示了如何利用这些布局管理器进行界面设计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

也在学习中,这些都是在莫烦python做志愿者写下的。~

部件布局和摆放


首先我们先看看我们常用的`pack()`
tk.Label(window, text='1').pack(side='top')#上
tk.Label(window, text='1').pack(side='bottom')#下
tk.Label(window, text='1').pack(side='left')#左
tk.Label(window, text='1').pack(side='right')#右

效果图是这样的:





接下里我们在看看`grid()`

for i in range(4):
    for j in range(3):
        tk.Label(window, text=1).grid(row=i, column=j, padx=10, pady=10)

以上的代码就是创建一个四行三列的表格,其实`grid`就是用表格的形式定位的。这里的参数
`row`为行,`colum`为列,`padx`就是单元格左右间距,`pady`就是单元格上下间距。


效果图:





再接下来就是`place()`

tk.Label(window, text=1).place(x=20, y=10, anchor='nw')

这个比较容易理解,就是给精确的坐标来定位,如此处给的`(20,10)`,就是将这个部件放在坐标为`(x,y)`的这个位置

后面的参数`anchor=nw`就是前面所讲的锚定点是西北角。

from tkinter import * # 导入tkinter库 def do_build(): # 新建文件 text.delete(0.0, 'end') # 清空文本框内容 def do_open(): # 打开文件 file_path = entry_file.get() # 获取输入的文件名 with open(file_path, encoding='utf-8') as fread: # 打开文件,此段代码结束后自动关闭 content = fread.read() # 读取文件内容 text.delete(0.0, 'end') # 清空文本框内容 text.insert('end', content) # 在光标后插入文件内容 def do_save(): # 保存文件 content = text.get(0.0, 'end') # 获取文本框内容 file_path = entry_file.get() # 文件路径 with open(file_path, 'w+', encoding='utf-8') as fwrite: fwrite.write(content) def do_find(): # 查找文字 search_str = tk.simpledialog.askstring("查找", "请输入要查找的内容:") if search_str: start_pos = self.text_area.search(search_str, 1.0, stopindex=tk.END) while start_pos: end_pos = f"{start_pos}+{len(search_str)}c" self.text_area.tag_add("match", start_pos, end_pos) self.text_area.tag_config("match", background="yellow", foreground="black") start_pos = self.text_area.search(search_str, end_pos, stopindex=tk.END) def do_replace(): # 替换文字 old_string = tk.simpledialog.askstring("替换", "请输入需要替换的文字:") new_string = tk.simpledialog.askstring("替换", f"将 '{old_string}' 替换为?") if old_string and new_string: all_content = self.text_area.get(1.0, tk.END) updated_content = all_content.replace(old_string, new_string) self.text_area.delete(1.0, tk.END) self.text_area.insert(tk.END, updated_content) win = Tk() # 创建窗口 win.title('文本编辑器') # 设置标题 win.geometry('860x600') entry_file = Entry(win) # 创建一个文本输入框 btn_build = Button(win, text='新建', command=do_build) # 创建按钮用于新建文件 btn_open = Button(win, text='打开', command=do_open) # 创建按钮用于打开文件 btn_save = Button(win, text='保存', command=do_save) # 创建按钮用于保存文件 btn_find = Button(win, text='查找', command=do_find) # 创建按钮用于查找内容 btn_replace = Button(win, text='替换', command=do_replace) # 创建按钮用于替换内容 text = Text(win) # 创建多行文本框,用于编辑文件 entry_file.pack() # 放置各组件 btn_build.pack() btn_open.pack() btn_save.pack() btn_find.pack() btn_replace.pack() text.pack() win.mainloop() # 进入消息循环 如何把5个按钮放在同一行?
04-03
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值