Reputation: 3
I'm quite new to Tkinter and this is my first program, can anyone tell me why the canvas is not showing up? I'm not getting any errors so I assume it is working but just not visible? I tried moving it up a layer but it was still invisible. Here is my code:
from Tkinter import *
import Tkinter as tk
class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.frame = Frame(self.master)
self.master = master
self.window()
self.drawFigure()
# self.master.attributes('-fullscreen', True)
self.master.bind("<Escape>", self.end_fullscreen)
def window(self):
self.frame = Frame(self.master)
screen_width = self.frame.winfo_screenwidth() / 2
screen_height = self.frame.winfo_screenheight() / 2
self.master.geometry('%dx%d' % (screen_width, screen_height))
def end_fullscreen(self, event=None):
self.master.attributes("-fullscreen", False)
def drawFigure(self):
self.frame = Frame(self.master)
self.C = Canvas(self.frame, width=200, height=200, bg = 'red')
self.C.pack()
self.C.create_rectangle(50, 20, 150, 80, fill="#476042")
if __name__ == '__main__':
root = tk.Tk()
w = Application(root)
w.master.mainloop()
Appreciate all the input.
Upvotes: 0
Views: 3194
Reputation: 7176
You import Tkinter and Tkinter as tk, which gets confusing.
Application
inherits from Frame so you don't have to create additional frames inside. Certainly not more than one named self.frame
.
How about this:
from Tkinter import *
class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.master = master
self.pack()
self.window()
self.drawFigure()
self.master.bind("<Escape>", self.end_fullscreen)
def window(self):
screen_width = self.winfo_screenwidth() / 2
screen_height = self.winfo_screenheight() / 2
self.master.geometry('%dx%d' % (screen_width, screen_height))
def end_fullscreen(self, event=None):
self.master.attributes("-fullscreen", False)
def drawFigure(self):
self.C = Canvas(self, width=200, height=200, bg = 'red')
self.C.pack()
self.C.create_rectangle(50, 20, 150, 80, fill="#476042")
if __name__ == '__main__':
root = Tk()
w = Application(root)
w.master.mainloop()
Upvotes: 1
Reputation: 365617
You’re creating three sub frames of your parent, storing each of them as self.frame
(so all but the last one are lost), and not placing any of them anywhere.
So, you’ve correctly placed the canvas on one of these invisible frames, but that doesn’t do any good.
I’m not sure what you’re trying to do with all these separate frames.
self
rather than self.master
.self
instead of self.frame
.Upvotes: 1
Reputation: 71
You forgot to call pack()
on the Frame you created in drawFigure()
:
def drawFigure(self):
self.frame = Frame(self.master)
self.frame.pack() # <--- There
self.C = Canvas(self.frame, width=200, height=200, bg = 'red')
self.C.pack()
self.C.create_rectangle(50, 20, 150, 80, fill="#476042")
Upvotes: 1