【问题标题】:How to make tkinter's GUI components dynamic?如何使 tkinter 的 GUI 组件动态化?
【发布时间】:2021-02-24 08:43:29
【问题描述】:

我正在为 Windows 制作一个 tkinter 应用程序,我想让小部件放置动态化。就像在this picture 中一样,Label(它就像一个背景图像支架)覆盖了 Y 轴,但是当我最大化窗口时,比如here,照片并没有覆盖整个 Y 轴.

如何解决这个问题,或者有没有办法在不使用root.overridedirect() 的情况下禁用窗口的最大化按钮?

这里是代码→

#importing everything
from tkinter import *
from pypresence import Presence
import time


#making the root window
root = Tk()

dimension = (
    800,
    500
)
#setting the window
bg = PhotoImage(file = r'C:\Users\Hunter\Desktop\school 1\module\pbm\bg.png')
background = Label(root, bd=0, image=bg)
background.place(x=0, y=0, relwidth=1, relheight=1)

root.geometry(f'{dimension[0]}x{dimension[1]}')


#main thing
root.mainloop()

【问题讨论】:

  • 试试background.pack(fill="both") 而不是background.place(x=0, y=0, relwidth=1, relheight=1)
  • 使用root.resizable(0, 0) 禁用maximize 按钮。否则,无论何时调整根窗口的大小,您都需要调整图像大小。
  • 拥有动态 tkinter 应用程序的第一步是使用网格或打包方法而不是放置。
  • 您可以使用root.resizable(0, 0)禁用最大化按钮。

标签: python python-3.x user-interface tkinter tkinter-label


【解决方案1】:

你可以通过绑定一个事件处理函数来做你想做的事,这样每当root窗口<Configure>事件发生时它就会被调用。这将允许您在根窗口移动或调整大小时更改Label 所附图像的大小。

在下面的代码中,PIL(Python 图像库)的Pillow fork 用于调整图像大小,因为tkinter 不提供执行此操作的本机方式。原始图像单独存储,所有需要在Label 上进行的缩放始终与其大小相关。这可以防止错误累积和降低显示的图像。

请注意,我还将您的 from tkinter import * 更改为 import tkinter as tk,因为 tkinter.ImagePIL.Image 之间存在冲突。通常最好避免import * 以防止这种情况发生。

from PIL import Image, ImageTk
import tkinter as tk
import time


DIMENSION = 800, 500

def config_callback(event):
    global bg
    window_w, window_h = root.winfo_width(), root.winfo_height()

    # New height of image is original height * ratio of current to starting size of window.
    new_height = round(orig_height * (window_h/DIMENSION[1]))
    # Resize original image to this new size (without changing width).
    bg = ImageTk.PhotoImage(orig_img.resize((orig_width, new_height), Image.ANTIALIAS))
    background.config(image=bg)

root = tk.Tk()

#image_path = r'C:\Users\Hunter\Desktop\school 1\module\pbm\bg.png'
image_path = r'.\bkgr.png'

orig_img = Image.open(image_path)
orig_width, orig_height = orig_img.size
bg = ImageTk.PhotoImage(orig_img.resize((orig_width, orig_height), Image.ANTIALIAS))

background = tk.Label(root, bd=0, image=bg)
background.place(x=0, y=0, relwidth=1, relheight=1)

root.geometry(f'{DIMENSION[0]}x{DIMENSION[1]}')
root.bind('<Configure>', config_callback) # Callback on window move/resize

root.mainloop()

这是一个屏幕截图,显示了它最初的样子:

这是另一个显示更改窗口高度后的样子:

【讨论】:

    猜你喜欢
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多