【问题标题】:Python: How to make Pillow and Tkinter compatible?Python:如何使 Pillow 和 Tkinter 兼容?
【发布时间】:2018-09-05 01:30:27
【问题描述】:

我正在尝试运行一些同时使用 tkinter 和 Pillow 的 Python 代码。当我在我的 IDE (Pycharm) 中运行代码时,程序会打开并且没有问题。但是,当我尝试将代码作为 Python 文件单独运行时,我会快速闪现命令提示符,该提示符会立即关闭。我正在运行 Python 3.7.0(最新版本),这意味着我还有最新版本的 tkinter 以及 Pillow 5.2.0。如何让我的代码在其 UI 中作为独立的 python 文件运行?

from tkinter import *
from PIL import Image, ImageTk

root = Tk()

mapFrame=Frame(root)
mapFrame.place(relx=0, rely=0, relheight=0.85, relwidth=1)
subMapFrame = Frame(mapFrame)
subMapFrame.place(relx=0.05,rely=0.1,relwidth=0.9, relheight=0.9)

image = Image.open("field.png")
img_copy= image.copy()
background_image = ImageTk.PhotoImage(image)
background = Label(subMapFrame, image=background_image)
background.pack(fill=BOTH, expand=YES)

root.mainloop()

【问题讨论】:

    标签: python tkinter python-imaging-library tk


    【解决方案1】:

    将以下代码添加到 python 文件的末尾。

    input('Press any key to exit')

    它会阻止命令提示符立即关闭,除非你按下某些键。

    【讨论】:

    • 我尝试在 root.mainloop 行之前和之后添加代码行。仍然无法打开用户界面。
    • @KeenanB 你能在mapFrame=Frame(root) 中定义宽度和高度吗?
    • 我尝试更改两个框架,以便将宽度和高度定义为:mapFrame=Frame(root,width=150,height=150) mapFrame.place(x=0, y=0) subMapFrame = Frame(mapFrame, width=100, height=100) subMapFrame.place(x=0,y=0)
    • 你检查图像是否存在。因为如果我将图像路径更改为不存在,提示会立即关闭。
    • 当你双击运行时,你是通过安装在你电脑上的python而不是pycharm来运行它。你也需要为你的 python 安装枕头。一个好的检查方法是右键点击py文件,点击edit by ide,然后运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-31
    • 2020-04-13
    • 2022-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多