使用tkinter编写番茄钟时调用Canvas.create_text报类型错误求助
番茄钟Tkinter代码错误解决
你的番茄钟代码触发了AttributeError: 'int' object has no attribute '_create'错误,问题根源在于调用create_text的方式有误。
原代码问题片段
from tkinter import * window = Tk() window.title('Pomodoro timer') window.config(padx=100, pady=50) canvas = Canvas(width=200, height=224) tomato_img = PhotoImage(file="C:/vscode/tomato.png") canvas.create_image(102, 112, image=tomato_img) # 错误:直接用类名调用实例方法 Canvas.create_text(102, 112, text='00:00') canvas.pack() window.mainloop()
错误原因
Canvas是tkinter中的类,create_text是实例方法——必须通过你创建好的canvas对象调用,不能直接用类名调用。当你写Canvas.create_text(102, 112, text='00:00')时,Python会把第一个参数102当成方法要求的self参数(即Canvas实例),但整数102没有_create方法,因此抛出错误。
修正后的代码
把Canvas.create_text改为canvas.create_text即可解决问题:
from tkinter import * window = Tk() window.title('Pomodoro timer') window.config(padx=100, pady=50) canvas = Canvas(width=200, height=224) tomato_img = PhotoImage(file="C:/vscode/tomato.png") canvas.create_image(102, 112, image=tomato_img) # 改为通过实例对象调用方法 canvas.create_text(102, 112, text='00:00') canvas.pack() window.mainloop()
内容的提问来源于stack exchange,提问作者Anuja Dilshan
相关产品推荐
相关产品推荐

