首页 > 解决方案 > PNG不会在弹出窗口Tkinter中显示

问题描述

尽管我的 img 变量是全局变量,但我的 PNG 文件不会显示在我的弹出窗口中。

global img

def Malwind():
    maltop = Toplevel()
    maltop.iconbitmap('icon.ico')
    maltop.title("Expert Systems Diagnosis Results")
    mgt1 = Label(maltop, text="The breast lump is diagnosed to be: Malignant").grid(row=5, column=2)
    mgt2 = Label(maltop, text="The following symptoms could be observed").grid(row=6, column=2)
    mgt3 = Label(maltop, text="Skin irritation\nPain or tenderness of the nipple\nBloody nipple discharge").grid(row=7, column=2)
    canvas = Canvas(maltop, width = 200, height = 200)
    canvas.grid(row = 1, column = 2)
    img = ImageTk.PhotoImage(Image.open("soft.png"))
    canvas.create_image(0, 0, anchor = NW, image = img)

标签: pythontkinter

解决方案


Global关键字应该在函数内,并允许函数在函数内修改全局范围内的变量。这意味着您必须global img进入函数,并确保该变量已经存在于全局范围内。这是更正后的代码:

def Malwind():
    global img
    maltop = Toplevel()
    maltop.iconbitmap('icon.ico')
    maltop.title("Expert Systems Diagnosis Results")
    mgt1 = Label(maltop, text="The breast lump is diagnosed to be: Malignant").grid(row=5, column=2)
    mgt2 = Label(maltop, text="The following symptoms could be observed").grid(row=6, column=2)
    mgt3 = Label(maltop, text="Skin irritation\nPain or tenderness of the nipple\nBloody nipple discharge").grid(row=7, column=2)
    canvas = Canvas(maltop, width = 200, height = 200)
    canvas.grid(row = 1, column = 2)
    img = ImageTk.PhotoImage(Image.open("soft.png"))
    canvas.create_image(0, 0, anchor = NW, image = img)

推荐阅读