#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. 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. 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? 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.
Also, the method name display_button
is a bit redundant. 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
.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.