python Tkinter Button 按键报错

python Tkinter Button 按键报错


from tkinter import *
from tkinter.messagebox import *
from PIL import Image
win=Tk()#界面开头
win.title("奶茶店")
win.geometry('960x800')
win.maxsize(1200,1000)
win.minsize(600,400)
#大标题
l1=Label(win,text='欢迎来到茶百道',font=('微软雅黑',28),fg = '#A066D3',bg="#DDA0DD")
l1.pack()
#分类
l2=Label(win,text='时令草莓季',font=('微软雅黑',24),fg = '#63B8FF',bg="#FFE4C4",width=10,height=1)
l2.place(x=10, y=80)
l3=Label(win,text='坦洋工夫茶',font=('微软雅黑',24),fg = '#63B8FF',bg="#FFE4C4",width=10,height=1)
l3.place(x=10, y=280)
l4=Label(win,text='坦洋工夫茶',font=('微软雅黑',24),fg = '#63B8FF',bg="#FFE4C4",width=10,height=1)
l4.place(x=10, y=480)
l5=Label(win,text='冷翠茶',font=('微软雅黑',24),fg = '#63B8FF',bg="#FFE4C4",width=10,height=1)
l5.place(x=10, y=680)
def Hanshu():
    top = Toplevel()#弹出新窗口
    l2=Label(win,text='时令草莓季',font=('微软雅黑',24),fg = '#63B8FF',bg="#FFE4C4",width=10,height=1)
    l2.place(x=10, y=80)
    top.title("茶百道")
    top.geometry('960x800')
    top.maxsize(1200,1000)
    top.minsize(600,400)
    l3=Label(top,text='时令草莓季',font=('微软雅黑',24),fg = '#63B8FF',bg="#FFE4C4",width=10,height=1)
    l3.place(x=350, y=50)
    l4=Label(top,text='草莓奶冻',font=('微软雅黑',24),fg = '#63B8FF',bg="#FFE4C4",width=10,height=1)
    l4.place(x=170, y=120)
    l5=Label(top,text='多肉草莓芝士',font=('微软雅黑',24),fg = '#63B8FF',bg="#FFE4C4",width=10,height=1)
    l5.place(x=540, y=120)
    labelImage1=Label(top,image=image1,width=100,height=100)
    labelImage1.place(x=10,y=150)
image2 = Image.open("1.jpg")
image1=PhotoImage(image2)
b01=Button(win,text="pick",command=Hanshu,image=image1,width=20,height=3,cursor= "circle")
b01.place(x=25,y=150)

img

看起来你的代码有一个错误,在这行:

l2=Label(win,text='时令草莓季',font=('微软雅黑',24),fg = '#63B8FF',bg="#FFE4C4",width=10,height=1)

应该将 win 改为 top,因为这个标签是在 top 这个窗口内的。正确的代码应该是这样的:

l2=Label(top,text='时令草莓季',font=('微软雅黑',24),fg = '#63B8FF',bg="#FFE4C4",width=10,height=1)

这样就可以避免报错了。


另外,还有一些建议:

  • 建议使用 place 方法放置组件时给出精确的坐标,而不是使用 pack 方法。这样可以使界面布局更加精确,避免组件重叠或者挤在一起的情况。
  • 建议使用专门的图片软件(如 Photoshop)将图片压缩到适当的大小,以减少图片加载时的时间。这样可以让程序运行得更流畅。
  • 建议使用 with 语句来打开图片文件,这样可以保证图片文件在使用完后被正确关闭,避免资源浪费。

例如,你可以这样来打开图片文件:

with Image.open("1.jpg") as image2:
    image1 = PhotoImage(image2)

希望这些建议能够帮助你。