我是python的新手,正在为使用Python的事件创建一个倒数计时器,我注意到画布内的图像不会填满较大显示器上的整个屏幕,并且小部件在调整大小时不会调整大小窗户缩了。我该如何解决?任何帮助表示赞赏。谢谢!
import datetime
import tkinter as tk
import winsound
def round_time(dt, round_to):
seconds = (dt - dt.min).seconds
rounding = (seconds + round_to / 2) // round_to * round_to
return dt + datetime.timedelta(0, rounding - seconds, -dt.microsecond)
def ct():
def count():
now = round_time(datetime.datetime.now(), round_to=1)
eh = datetime.datetime(2019, 3, 30, 20, 30)
tte = eh - now
canvas.itemconfig(label_cd, text=str(tte))
root.after(50, count)
count()
root = tk.Tk()
winsound.PlaySound('Sound1.wav', winsound.SND_ASYNC + winsound.SND_LOOP)
root.bind('<space>', lambda a: winsound.PlaySound(None, winsound.SND_PURGE))
root.bind('<s>', lambda a: winsound.PlaySound('Sound1.wav', winsound.SND_ASYNC + winsound.SND_LOOP))
root.geometry('1920x1080')
root.attributes('-fullscreen', True)
root.bind('<Escape>', lambda e: root.attributes("-fullscreen", False))
root.bind('<F11>', lambda z: root.attributes("-fullscreen", True))
root.title("Earth Hour Countdown!")
now = round_time(datetime.datetime.now(), round_to=1)
eh = datetime.datetime(2019, 3, 30, 20, 30)
tte = eh - now
canvas = tk.Canvas(root, height=1000, width=600, highlightthickness=0)
canvas.place(relheight=1, relwidth=1)
bg_img = tk.PhotoImage(file="new.gif")
bg_label = canvas.create_image((682.5, 384), image=bg_img)
cte_logo = tk.PhotoImage(file="cte1.gif")
cte_label = canvas.create_image((690, 120), image=cte_logo)
logo = tk.PhotoImage(file="eh60.gif")
logo_canvas = canvas.create_image((715, 590), image=logo)
label_msg = canvas.create_text((410, 300), text="Earth Hour Countdown:", font="Calibri 60 bold", fill="#CDCEDF")
label_cd = canvas.create_text((1080, 300), text=str(tte), font="Calibri 60 bold", fill="#CDCEDF")
ehtime_label = canvas.create_text((700, 400), text=("Earth Hour: " + eh.strftime("%d-%m-%Y %H:%M:%S")), font="Calibri 60 bold", fill="#CDCEDF")
ct()
root.mainloop()
答案 0 :(得分:0)
要在Python中调整图像大小,请查看Python图像库(PIL)。 现有一些有关使用PIL的文章,这些文章帮助我编写了以下代码。通过从运行平台获取的屏幕尺寸和“正确”尺寸的图像的参考尺寸,可以轻松计算出重新调整尺寸的因子。然后,可以通过将此因子应用于参考屏幕尺寸(在这种情况下为270x185)下的图像尺寸,来获得展开/缩小显示所需的尺寸。其余代码仅扫描参考图像的文件夹(Assets_dir),将其打开并使用PIL.Image调整大小,然后将调整大小后的图像保存到新文件夹中。
import PIL.Image
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
width = 1920.0 # default screen width/height stored images are based on.
height = 1200.0
width_resize = screen_width/width # calculate resize factor needed to correctly display on current screen.
height_resize = screen_height/height
new_width = int(width_resize*270)
new_height = int(height_resize*185)
Assets_dir = os.getcwd() + '\\Assets\\'
files = list(os.scandir(Assets_dir))
for file in files:
file_ext = file.name[-3:]
file_basename = file.name[:-4]
if file_ext == 'gif':
temp_image = PIL.Image.open(Assets_dir + file.name)
temp_image = temp_image.resize((new_width, new_height), PIL.Image.ANTIALIAS)
temp_image.save(Assets_dir + r'/resize/' + file.name)