[英]Why are the 4 buttons not displaying?
#task is to create 4 buttons using the Canvas module in Tkinter
class Buttons:
def __init__(self, par2, par3, par4, par5, fill, xpos, ypos):
self.par2 = par2
self.par3 = par3
self.par4 = par4
self.par5 = par5
self.fill = fill
self.xpos = xpos
self.ypos = ypos
def display_button(self):
canvas.create_oval(self.par2, self.par3, self.par4, self.par5, fill=str(self.fill))
canvas.place(self.xpos, self.ypos)
#create the buttons using the parameters in def __init__
button1 = Buttons(100, 100, 300, 300, "grey", -25, 25)
button2 = Buttons(100, 100, 300, 300, "grey", 0, 0)
button3 = Buttons(100, 100, 300, 300, "grey", 100, 25)
button4 = Buttons(100, 100, 300, 300, "grey", 50, 50)
The window and canvas have already been created previously and work fine.窗口和画布之前已经创建并且工作正常。 Could someone tell me why nothing appears in the window when I run the program?
有人能告诉我为什么当我运行程序时窗口中什么都没有出现吗? Thanks
谢谢
It looks like you're not invoking the Buttons.display_button
method on your button instances.看起来您没有在按钮实例上调用
Buttons.display_button
方法。 Unless you do that, you can expect to see nothing.除非你这样做,否则你什么也看不到。
From the way your code is written, it looks like canvas
is a global tk.Canvas
object.从您编写代码的方式来看,
canvas
似乎是一个全局tk.Canvas
对象。 Anytime you invoke Buttons.display_button
, you are also calling canvas.place
, which is meant to be used as an alternative to canvas.pack
- are you sure that's what you want to do?任何时候你调用
Buttons.display_button
,你还呼吁canvas.place
,其目的是要被用来作为一种替代canvas.pack
-你确定这就是你想要做什么? Because, that doesn't seem right.因为,这似乎不太对。
I would start with something simpler (something that works) and go from there.我会从更简单的东西(有用的东西)开始,然后从那里开始。 A couple of other suggestions: I don't think
Buttons
is a good name for the class, since an instance of that class should represent a single button - Button
is a better name, I think.其他一些建议:我认为
Buttons
不是类的好名字,因为该类的实例应该代表一个按钮 - 我认为Button
是一个更好的名字。
Also, the method name display_button
is a bit redundant.此外,方法名称
display_button
有点多余。 We already know that this method "displays" a button by virtue of the fact that it's part of the Button
class - I would call it something like display
or render
.我们已经知道这个方法“显示”一个按钮,因为它是
Button
类的一部分——我会称它为display
或render
。
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=200, height=200)
canvas.pack()
class Button:
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def render(self):
canvas.create_oval(*self.args, **self.kwargs)
button = Button(50, 50, 150, 150, fill="grey")
button.render()
root.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.