原代码如下:
-
from tkinter
import *
-
from tkinter.filedialog
import askopenfilename
-
from PIL
import Image,ImageTk
-
-
class mainapp:
-
def __init__(self):
-
root=Tk()
-
root.title(
“Several”)
-
root.geometry(
‘200x300’)
-
Button(root,text=
‘自动取点’,command=self.another1).place(relx=
0.3,rely=
0.15,anchor=CENTER)
-
Button(root,text=
‘图片翻转’).place(relx=
0.7,rely=
0.15,anchor=CENTER)
-
root.mainloop()
-
def another1(self):
-
qudian()
-
def another2(self):
-
fanzhuan
-
-
class qudian:
-
def __init__(self):
-
r1=Tk()
-
r1.title(
‘自动取点’)
-
r1.geometry(
‘400x400’)
-
Label(r1,text=
‘图片路径:’).place(relx=
0,rely=
0.04)
-
e1=Entry(r1)
-
e1.place(relx=
0.15,rely=
0.04)
-
Button(r1,text=
‘选择图片’).place(relx=
0.52,rely=
0.02)
-
Label(r1,text=
“所选择的图片:”).place(relx=
0,rely=
0.13)
-
img_open=Image.open(
‘desert.jpg’)
-
img_open.thumbnail((
200,
200))
-
img=ImageTk.PhotoImage(img_open)
-
l1=Label(r1,image=img)
-
l1.place(relx=
0,rely=
0.18)
-
r1.mainloop()
-
class fanzhuan:
-
def __init__(self):
-
r2=Tk()
-
r2.mainloop()
-
mainapp()
运行以后报错:
之后去网上查了解决办法,在 https://zhidao.baidu.com/question/1800925191188288187.html 这个网址下找到了正确答案。因为在一个程序中只能存在一个根窗口,也就是说只能存在一个Tk(),其他的窗口只能以顶层窗口(Toplevel())的形式存在。
于是将qudian类下的Tk()改成Toplevel()后,问题完全解决。
修改后的代码:
-
class qudian:
-
def __init__(self):
-
r1=Toplevel()
-
r1.title(
'自动取点')
-
r1.geometry(
'400x400')
-
Label(r1,text=
'图片路径:').place(relx=
0,rely=
0.04)
-
e1=Entry(r1)
-
e1.place(relx=
0.15,rely=
0.04)
-
Button(r1,text=
'选择图片').place(relx=
0.52,rely=
0.02)
-
Label(r1,text=
"所选择的图片:").place(relx=
0,rely=
0.13)
-
img_open=Image.open(
'desert.jpg')
-
img_open.thumbnail((
200,
200))
-
img=ImageTk.PhotoImage(img_open)
-
l1=Label(r1,image=img)
-
l1.place(relx=
0,rely=
0.18)
-
r1.mainloop()
参考:https://stackoverflow.com/questions/26097811/image-pyimage2-doesnt-exist