python导入文件但图像无法识别

我创建了一个带有下拉菜单的 python 文件。当我选择选项一时,它会导入另一个 python 文件,其中有一个复选按钮和画布中的图片。文件和图片都位于同一文件夹中。代码导入文件导入画布和检查按钮,但我收到错误消息说图像“pyimage1”不存在。如果我单独运行第二个文件,它确实显示复选按钮和图像,没有错误。当导入 python 文件时,图像不再被识别,或者我做错了什么?有什么解决方法吗?


主要程序:


from tkinter import *


root = Tk()

root.geometry('1560x750')


canvas=Canvas(root)

canvas.config(width=1000, height=1560, bg='light grey')

canvas.grid(row=1,column=3, rowspan=1550,ipadx=1300,ipady=750,sticky=NW)


def option_number(x):

    if x == "one":

        import part2


variable = StringVar()

variable.set("options")

w = OptionMenu(canvas, variable, "one", "two",command = option_number)

w.config(width=15, height=1,bg='blue')

w.place(x=400,y=100)


root.mainloop()

要导入的文件:


from tkinter import *


root = Tk()

root.geometry('1560x750')


canvas=Canvas(root)

canvas.config(width=1000, height=1560, bg='light grey')

canvas.grid(row=1,column=3, rowspan=1550,ipadx=1300,ipady=750,sticky=NW)


button = Checkbutton(canvas).place(x=170, y=230)

AND_gate=PhotoImage(file='AND.png') #set up variables for and_gate

labelimage_and = Label(canvas, image=AND_gate).place(x=200,y=200)


root.mainloop()

更新了导入函数的代码:


from tkinter import *


root = Tk()

root.geometry('1560x750')


canvas=Canvas(root)

canvas.config(width=1000, height=1560, bg='light grey')

canvas.grid(row=1,column=3, rowspan=1550,ipadx=1300,ipady=750,sticky=NW)


def option_number(x):

    if x == "one":

        from part1 import import_def


variable = StringVar()

variable.set("options")

w = OptionMenu(canvas, variable, "one", "two",command = option_number)

w.config(width=15, height=1,bg='blue')

w.place(x=400,y=100)


root.mainloop()

凤凰求蛊
浏览 172回答 1
1回答

当年话下

这是我知道如何在 tkinter 中导入文件和函数的方法,不确定这是否是正确的方法,但看看我对这两个文件所做的更改main.py:from tkinter import *from function import import_defroot = Tk()root.geometry('1560x750')canvas=Canvas(root)canvas.config(width=1000, height=1560, bg='light grey')canvas.grid(row=1,column=3, rowspan=1550,ipadx=1300,ipady=750,sticky=NW)def option_number(x):    if x == "one":        import_def()variable = StringVar()variable.set("options")w = OptionMenu(canvas, variable, "one", "two",command = option_number)w.config(width=15, height=1,bg='blue')w.place(x=400,y=100)root.mainloop()和函数.py:from tkinter import *def import_def():    root = Toplevel()    root.geometry('1560x750')    canvas2 = Canvas(root)    canvas2.config(width=1000, height=1560, bg='red')    canvas2.grid(row=1, column=3, rowspan=1550, ipadx=1300, ipady=750, sticky=NW)    button = Checkbutton(canvas2).place(x=170, y=230)    AND_gate=PhotoImage(file='sad songs.jpg') #set up variables for and_gate    labelimage_and = Label(canvas2, image=AND_gate).place(x=200,y=200)    root.mainloop()希望对您有帮助,如有疑问或错误,请告诉我。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python