【发布时间】:2020-11-29 08:43:51
【问题描述】:
我对 python 还很陌生,并试图掌握它的类和函数。我之前写了一个代码,为了让它干净,我试图把它放在类中,但是它的一些元素不再显示了。
代码应该显示一个带有文本的白色圆角矩形和一个按钮,它做得很好,但是当我添加分类时,按钮和文本不显示。
这可能只是一些小东西,但正如我所说,我正在努力学习 - 如何让它像使用 OOP 之前一样显示?我究竟做错了什么?感谢您的帮助!
我的代码如下。
root = Tk()
root.configure(bg="steel blue")
canvas = Canvas(root, highlightthickness=0)
canvas.config(width=350, height=250,
bg="steel blue", ) # canvas.config(width = root.winfo_screenwidth(), height = root.winfo_screenheight() )
canvas.pack()
class User_Identification(object):
def User_Id(self):
canvas.delete("all") # root.configure(bg = "white") #canvas.config(bg = "white")
canvas.config(width=505, height=505,
bg="steel blue") # canvas.config(width = root.winfo_screenwidth(), height = root.winfo_screenheight() )
box = canvas.create_rectangle(40, 20, 500, 500, fill="white", width=4)
canvas.create_text(255, 65, text="Who are you?", font=("comic sans", 30))
box2 = canvas.create_rectangle(50, 30, 450, 100, width=2)
canvas.move(box2, 9, 5)
canvas.place(relx=0.5, rely=0.5, anchor=CENTER)
User_button = Button(root, text="User", anchor=CENTER, command=Per_Form)
User_button.configure(width=45, height=6, bg="white", fg="black", border=10) # height
User_button = canvas.create_window(60, 150, anchor=NW, window=User_button)
Driver_button = Button(root, text="Driver", anchor=CENTER, command=Per_Form)
Driver_button.configure(width=45, height=6, bg="white", fg="black", border=10) # height
Driver_button = canvas.create_window(60, 300, anchor=NW, window=Driver_button)
class Rectangle:
def round_rectangle(x1, y1, x2, y2, radius=25, **kwargs): # Making of the round rectangle
points = [x1 + radius, y1,
x1 + radius, y1,
x2 - radius, y1,
x2 - radius, y1,
x2, y1,
x2, y1 + radius,
x2, y1 + radius,
x2, y2 - radius,
x2, y2 - radius,
x2, y2,
x2 - radius, y2,
x2 - radius, y2,
x1 + radius, y2,
x1 + radius, y2,
x1, y2,
x1, y2 - radius,
x1, y2 - radius,
x1, y1 + radius,
x1, y1 + radius,
x1, y1]
return canvas.create_polygon(points, **kwargs, smooth=True)
my_rectangle = round_rectangle(10, 60, 330, 250, radius=23, outline="black", fill="white", width=4)
def __init__(self, Next_button):
self.Next_button = Next_button
Next_button = Button(root, text="Next", anchor=CENTER, command=User_Identification)
Next_button.configure(width=10, bg="black", fg="blue", border=10)
canvas.create_window(500, 500, anchor=NW, window=Next_button)
def text(text):
text = canvas.create_text(170, 100, text="Hey there, welcome to DeliverToday! \nWe bring your needs right at your doorstep ~ \nhave a great journey ahead!")
canvas.place(relx=0.5, rely=0.5, anchor=CENTER)
【问题讨论】:
-
创建
User_Identification类的实例绝对没有任何作用。它所有有意义的代码都在User_Id方法中,您永远不会调用它。要么显式调用它,要么将方法重命名为__init__,以便在实例化类时自动调用它。 -
@jasonharper 好的,但当前的问题是按钮和文本根本不显示!这就是我的问题所在,我该怎么办?
-
Next类的类似问题 - 你甚至从未实例化它,更不用说调用它的任何一个方法了。 -
您最好先阅读更多有关 OOP 的内容,否则您将永远无法理解其他人对您代码中的问题的看法。
-
@acw1668:“你最好先阅读更多关于 OOP 的内容”听起来有点冒犯,而且没有任何帮助。
标签: python python-3.x oop tkinter tkinter-canvas