python - 如何将按钮放在图像顶部?(tkinter)
问题描述
如何将按钮放在图像上并将其保持在窗口的中心?代码工作正常,但按钮在图像下方,我无法单击它
from tkinter import Frame, Tk, Label, Button
from PIL import Image, ImageTk
class Example(Frame):
def __init__(self, master, *pargs):
Frame.__init__(self, master, *pargs)
self.image = Image.open("folder\\file.gif")
self.img_copy= self.image.copy()
self.background_image = ImageTk.PhotoImage(self.image)
self.background = Label(self, image=self.background_image)
self.background.pack(fill="both", expand="YES")
self.background.bind('<Configure>', self._resize_image)
def _resize_image(self,event):
new_width = event.width
new_height = event.height
self.image = self.img_copy.resize((new_width, new_height))
self.background_image = ImageTk.PhotoImage(self.image)
self.background.configure(image = self.background_image)
root = Tk()
root.title("Title")
root.geometry("600x600")
root.configure(background="black")
e = Example(root)
e.pack(fill="both", expand="YES")
btn=Button(root,text="Hello World").pack()
root.mainloop()
解决方案
我不知道这是否是您真实应用程序的正确解决方案,但对于问题中的代码,最简单的解决方案是使用place
. 您可以使用place
相对位置来保持一个小部件在另一个小部件中居中。
place
作为通用布局管理器也不是最好的,但对于非常具体的用例,它是适合这项工作的工具。在以下示例中,使用、和将按钮放置在Example
框架的中心。该参数指定相对坐标相对于哪个小部件。relx
rely
anchor
in_
btn=Button(root,text="Hello World")
btn.place(in_=e, relx=.5, rely=.5, anchor="c")
推荐阅读
- html - 如何将html和js网站部署到heroku,procfile应该是什么?
- vue.js - 如何在vue中的不同if语句上添加类
- r - Matlab 和 R 图像处理输出之间的差异
- kubernetes - 如何从 EKS 集群中删除 pod?
- angular - 在 Angular Ivy 中,为什么在 View Engine 中的用法之间没有缓存纯管道实例?
- modbus - 带有 RTU 成帧器的 Pymodbus 异步服务器不工作
- html - getbootstrap.com vs bootstrapdocs.com:这些应该是相同的东西吗?
- swift - 如果有非英文字符SwiftUI如何处理URL图像
- c# - .net 5.0 AssemblyLoadContext 中的插件
- android - 如何访问可组合内的@Composable 属性?