[英]How do I make my widgets in tkinter adjust their size automatically with respect to the window size?
[英]how do i add an image to my tk window and make it automatically rezize the window to the image size
我不知道如何将图像添加到 window,而且我对 python/编码的经验很少
这是我目前使用的代码,可以用来给它上色,但我不知道如何把它变成一张图片,在谷歌上搜索了 30 分钟后,我无法弄清楚
import random
from time import sleep
from tkinter import *
x = random.randint(7,20)
y = random.randint(7,20)
h = random.randint(200,300)
w = random.randint(200,300)
class Window(Tk):
def __init__(self):
Tk.__init__(self)
self.width = w
self.height = h
self.velx = x
self.vely = y
self.pos = (250,250)
self.geometry(f"{self.width}x{self.height}+{self.pos[0]}+{self.pos[1]}")
self.configure(background='#29a32d')
def moveWin(self):
x = self.pos[0] + self.velx
y = self.pos[1] + self.vely
downx, downy = x+self.width, y+self.height
sWidth = self.winfo_screenwidth() # gives 1366
sHeight = self.winfo_screenheight() # gives 1080
if x <= 0 or downx >= sWidth:
self.velx = -self.velx
if y <= 0 or downy >= sHeight:
self.vely = -self.vely
self.pos = (x,y)
self.geometry(f"+{x}+{y}")
return [x, y, downx, downy]
root = Window()
while True:
root.update()
pos = root.moveWin()
print(pos)
sleep(0.01)
要向 window 添加图像,您可以使用PhotoImage()
加载支持的图像(PNG、GIF),然后使用Label
显示图像:
...
class Window(Tk):
def __init__(self):
Tk.__init__(self)
self.width = w
self.height = h
self.velx = x
self.vely = y
self.pos = (250,250)
self.geometry(f"{self.width}x{self.height}+{self.pos[0]}+{self.pos[1]}")
self.configure(background='#29a32d')
# load the image
self.image = PhotoImage(file="/path/to/your/image.png")
# show the image using label
Label(self, image=self.image).pack()
...
请注意,不建议在 tkinter 应用程序中使用 while 循环,使用 .after .after()
替换 while 循环:
...
root = Window()
def move():
root.moveWin()
root.after(10, move)
# start the after loop
move()
root.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.