我正在学习Python3中的tkinter GUI。我正在制作一个有椭圆形和纽扣的画布。我想点击按钮,椭圆的宽度增加。按钮和椭圆形似乎很好。单击按钮时,没有任何反应,我收到以下错误消息。
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\amjones20\AppData\Local\Programs\Python\Python36-32\Lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:/Users/amjones20/PycharmProjects/gui/guiPractice1.py", line 13, in oval_change
Canvas.itemconfigure(self, oval, width=3)
NameError: name 'oval' is not defined
对我而言,oval_change
函数似乎无法识别self.oval
函数中的__init__
。我不确定如何正确定义oval
,以便在调用oval_change
函数时识别它。代码如下
from tkinter import *
class GUI(Canvas):
def __init__(self, master):
self.canvas = Canvas(master, width=600, height=600)
self.canvas.pack()
self.oval = self.canvas.create_oval(100,500,500,100)
def oval_change(self):
Canvas.itemconfigure(self, oval, width=3)
def button_appear(self):
self.button1 = Button(root, text="button", command=self.oval_change)
self.button1_window = self.canvas.create_window(200, 200, window=self.button1)
root = Tk()
hex = GUI(root)
hex.button_appear()
root.mainloop()
答案 0 :(得分:2)
首先,这不是一个tkinter问题。 Tkinter类与任何其他python类没有什么不同,初始化规则几乎相同。
考虑以下代码:
class GUI(Canvas):
def __init__(self, master):
self.canvas = Canvas(master, width=600, height=600)
self.canvas.pack()
您正在定义一个继承自Canvas
的类。第一个问题是你没有正确调用超类的构造函数,所以它没有完全构造。
接下来,您将在此画布中创建另一个画布。
由于您的自定义类本身是Canvas
,因此无需创建第二个画布。您只需要正确初始化您正在创建的类,然后使用实例本身创建椭圆:
class GUI(Canvas):
def __init__(self, master):
Canvas.__init__(self, master, width=600, height=600)
self.oval = self.create_oval(100,500,500,100)
接下来,错误消息是name 'oval' is not defined
。这是因为您正在创建self.oval
但不是oval
。您需要使用self.oval
。此外,您可以在self
而不是类:
def oval_change(self):
self.itemconfigure(self.oval, width=3)
最后,创建画布的代码应该负责将它放在窗口中:
hex = GUI(root)
hex.pack(fill="both", expand=True)
这是完整的程序:
from tkinter import *
class GUI(Canvas):
def __init__(self, master):
Canvas.__init__(self, master, width=600, height=600)
self.oval = self.create_oval(100,500,500,100)
def oval_change(self):
self.itemconfigure(self.oval, width=3)
def button_appear(self):
self.button1 = Button(self, text="button", command=self.oval_change)
self.button1_window = self.create_window(200, 200, window=self.button1)
root = Tk()
hex = GUI(root)
hex.pack(fill="both", expand=True)
hex.button_appear()
root.mainloop()