【问题标题】:Tkinter canvas not showing imageTkinter 画布不显示图像
【发布时间】:2016-12-07 09:41:02
【问题描述】:

我可以让 tkinter 显示窗口或背景图像,有没有人建议如何同时显示两者(我希望对象进入背景图像),我的代码如下:

from tkinter import *
from tkinter import ttk


root= Tk()
# Code to add widgets will go here...
root.title("MTGO Daily Decklists")
def test():
    print("things")

# pick a .gif image file you have in the working directory
# or give full path
image1 = PhotoImage(file="backgroundimage.gif")
w = Canvas(root, width=800, height=700,)
background = PhotoImage(file = "backgroundimage.gif")
w.create_image(500, 500, image=image1)
w.pack()
format_mtg= StringVar()
format_entry= ttk.Entry(w, width=25, textvariable=format_mtg)
format_entry_window = w.create_window(10, 10, anchor='n', window=format_entry)
format_entry.pack()
date= StringVar()
date_entry=ttk.Entry(root, width=25, textvariable=date)
date_entry_window = w.create_window(10, 10, anchor='n', window=date_entry)
date_entry.pack()
ttk.Label(w, text="input format here").pack()
ttk.Button(w, text="fetch", command=test).pack()
ttk.Label(w, text="input date here").pack()
sortby= StringVar()
sortby_entry= ttk.Entry()
sortby_entry.pack()
ttk.Label(w, text="input how you want the decklists to be sorted").pack()
root.mainloop()

【问题讨论】:

  • 我没有看到任何从背景图像创建画布图像的尝试。
  • 哎呀,我把 w.create_image(500, 500, image=image1) 改成了 w.create_image(500, 500, image=background) 但还是有同样的问题
  • 当您将其更改为image=background 时,您是添加了一行来为image1 创建画布图像,还是只创建了一个图像?
  • 只有一张图片,我读到您需要在某处保留对图片的引用,以便在 tkinter 关闭时不会删除它
  • 如果你想打印两个对象ab,你试试print(a),看到它只打印a,把它改成print(b),看到它只打印b,然后推断不可能打印两件事?或者你会用print(a) 写一行,然后用print(b)另一行

标签: python python-3.x tkinter python-imaging-library tkinter-canvas


【解决方案1】:

您将图像的中心放置在 500x500 处。但是,程序启动后,您的窗口只有大约 300x200。您的图像可能在那里,但不在屏幕的可见部分。

即使您将画布的大小设置为 800x700,您还是在画布内打包了小部件。这会导致画布收缩以适应其内容。更复杂的是,在打包画布时不要使用 expandfill 选项,因此最终结果是 GUI 的内部缩小到最小尺寸。

注意:如果您使用create_window 将窗口添加到画布,您应该在该窗口上也调用gridpack。您需要致电create_windowpack,但不能同时致电两者。无论您最后调用哪个,都会有任何效果。

解决方案有很多,选择哪种取决于您的最终目标。如果您希望无论窗口大小或其内容大小如何都将画布强制为 800x700 的高度,您可以关闭画布内部的几何传播。例如:

w.pack_propagate(False)

您还可以打包画布以填充给定的空间,然后将背景图像锚定到左上角。例如:

w.pack(fill="both", expand=True)
w.create_image(0, 0, image=image1, anchor="nw")

您也可以停止使用画布,并将背景图像放在标签中。然后,您可以使用place 将标签置于主窗口的中心。例如:

background_label = Label(root, image=image1)
background_label.place(relx=.5, rely=.5)

【讨论】:

    猜你喜欢
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 2015-11-29
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2013-12-02
    相关资源
    最近更新 更多