Tkinter按钮显示异常求助:按钮出现在非目标窗口
问题分析与解决方案
嘿,我一眼就看出问题出在哪啦!你遇到的按钮跑到其他窗口的情况,是Tkinter里非常常见的小失误——你创建按钮时没有指定它们的父窗口,导致这些按钮默认绑定到了程序原来的主窗口,而不是你新弹出的fen窗口。
具体原因
看你代码里创建按钮的部分:
a=Button(text='Rejouer', command=start, bg="#CDCCCD") a.grid() a.place(x=0, y=355, height= 25, width=605) b=Button(text='Quitter', command=fen.destroy, bg="#CDCCCD") b.grid() b.place(x=0, y=380, height= 25, width=605)
这里的Button没有传入第一个参数(父组件),Tkinter会自动把程序的根窗口作为这些按钮的父容器,所以按钮自然会出现在旧窗口里,而不是你新建的Toplevel窗口fen中。
另外还有个小问题:你同时给按钮用了grid()和place()两种布局方法,这会导致布局逻辑冲突,建议只保留其中一种(这里用place()更符合你的需求,直接去掉grid()调用即可)。
修复后的代码
把按钮的创建代码修改为指定父窗口fen,并移除多余的grid()调用:
def question(): global n can.itemconfig(nvqst, text="Nouvelle question:", fill="white", font=("Helvetica", '11')) if len(qst)<0: return if len(qst)==1: fen2.destroy() a=False with open("score.txt","w") as storage: storage.write(str(score)) fen=Toplevel() fen.title("Quizz") can2 = Canvas(fen, height=400, width=600, background='grey') fichier=open('score.txt','r') scorex=fichier.readline() image=PhotoImage(file='fin.gif') scorevarx=can2.create_text(330,200, text= scorex) def start(): exec(open("C:\\Users\\Mohand\\Desktop\\python\\test27.py").read()) can2.create_image(0, 0, image=image, anchor=NW) can2.create_text(377, 110, text=score, anchor=W, font='arial') # 修复1:指定按钮的父窗口为fen a=Button(fen, text='Rejouer', command=start, bg="#CDCCCD") # 修复2:移除多余的grid(),保留place()即可 a.place(x=0, y=355, height= 25, width=605) b=Button(fen, text='Quitter', command=fen.destroy, bg="#CDCCCD") b.place(x=0, y=380, height= 25, width=605) can2.grid() fen.mainloop()
额外提醒
以后在Tkinter中创建任何组件(Button、Label、Canvas等)时,一定要记得明确指定父组件,这样才能确保组件出现在你期望的窗口或容器里,避免类似的布局错位问题~
内容的提问来源于stack exchange,提问作者Momo
相关产品推荐
相关产品推荐

