首页 > 解决方案 > 使用 X 和 Y 滚动条在 tkinter 窗口中添加图像作为背景

问题描述

我正在开发一个Python 3 tkinter应用程序,该应用程序使用带有垂直和水平(鼠标可滚动)滚动条的窗口,沿着窗口的尺寸。但我无法在同一窗口上显示.png图像作为背景。

我已经完成了使用标签和画布添加.png图像作为背景的方法,但不是图片,我只能在没有被框架覆盖的窗口区域看到白色。此外,我发现 canvas 方法真的很难,因为很难在其上放置框架,而框架又具有标签、按钮、滚动条等。我也尝试过使用PIL模块,但我发现从它的路径导入它时遇到问题(我也不认为这有多大帮助,因为我只是想使用.png图像)。

关于如何让滚动条和背景图像在同一个 tkinter 窗口中工作的任何建议?

#Function to create tkinter window with horizontal and vertical scrollbars

from tkinter import *
from tkinter import ttk
def win():
    r0=Tk()
    r0.title('title')
    f=Frame(r0,bg='BLACK')
    f.pack(fill=BOTH, expand=1)
#Creating canvas for attaching scrollbars
    c=Canvas(f,bg='BLACK')
    c.pack(side=LEFT, fill=BOTH, expand=1)
    s1=ttk.Scrollbar(f, orient=VERTICAL, command=c.yview)
    s2=ttk.Scrollbar(f, orient=HORIZONTAL, command=c.xview)
    s1.pack(side=RIGHT, fill=Y)
    c.configure(yscrollcommand=s1.set)
    s2.pack(side=BOTTOM, fill=X)
    c.configure(xscrollcommand=s1.set)
    c.bind('<Configure>', lambda e:c.configure(scrollregion=c.bbox('all')))
#Function to enable mouse scroll
    def mw(event):
        c.yview_scroll(-1*int((event.delta/120)), 'units')
    c.bind_all('<MouseWheel>', mw)
    r=Frame(c, bg='BLACK')
    c.create_window((0,0),window=r, anchor='s')
    return r, r0
r,r0=win()
#Adding images as background in tkinter window using labels

r=Tk()
# Adjust size 
r.geometry("800x800")
bg=PhotoImage(file="Your_img.png")
# Show image using label
l1 = Label(r, image=bg)
l1.place(x=0, y=0)
#Adding images as background in tkinter window using canvas

r=Tk()
# Adjust size 
r.geometry("800x800")
bg=PhotoImage(file="Your_img.png")
c1=Canvas(r, width=800, height=800)
c1.pack(fill="both", expand=True)
# Display image
c1.create_image(0, 0, image=bg, anchor="nw")

标签: python-3.xtkinterscrollbarbackground-imagephotoimage

解决方案


推荐阅读