I have 2 seperate files and trying to make a sort of 'module' with this one file. But it does not work.
The background color is still this weird gray color even if I set it to say, black. Here is the 'module' file:
import tkinter as tk
class TUICanv:
global screenWidth, screenHeight
def __init__(self,win,bg="#232627"):
self.screenWidth = win.winfo_screenwidth()
self.screenHeight = win.winfo_screenheight()
self.canvas = tk.Canvas(win,width=self.screenWidth,height=self.screenHeight,background=bg)
self.background = bg
self.width = self.canvas.winfo_width()
self.height = self.canvas.winfo_height()
And here is the other file:
import tkinter as tk
import terkinter as tr
import os
import re
win = tk.Tk()
allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_"
win.title("Terminos")
canv = tr.TUICanv(win)
win.geometry(f'{canv.screenWidth}x{canv.screenHeight}')
canv.canvas.create_text(100,10,fill="darkblue",font="Times 20 italic bold",text="Click the bubbles that are multiples of two.")
win.mainloop()
The background does not change. It may be that the window in the other file is different, because I have only started tkinter 2 weeks ago.
2 Answers 2
Your canvas is not visible. One way to make it visible is to pack it by by adding
self.canvas.pack(fill="both", expand=True)
to your terkinter.py __init__ method.
1 Comment
pack on itself. That limits its usabiliity to only an application using pack. If the application switched to grid, this class would have to be modified.As others have pointed out, the problem is that you aren't making the widget visible by calling pack, place, or grid, or adding to the screen in some other method.
The simple solution is for your app to call one of those methods. For example:
...
win.title("Terminos")
canv = tr.TUICanv(win)
canv.cavas.pack(side="top", fill="both", expand=True)
...
That's not the best solution though, since it depends on the calling app to know that it implements an inner canvas. A better solution would be for your class to inherit from tk.Canvas. In that way it behaves just like the canvas.
For example:
import tkinter as tk
class TUICanv(tk.Canvas):
global screenWidth, screenHeight
def __init__(self,win,bg="red"):
self.screenWidth = win.winfo_screenwidth()
self.screenHeight = win.winfo_screenheight()
super().__init__(win,width=self.screenWidth, height=self.screenHeight,background=bg)
self.width = self.winfo_width()
self.height = self.winfo_height()
root = tk.Tk()
c = TUICanv(root)
c.pack(side="top", fill="both", expand=True)
root.mainloop()
pack,gridorplace) on the canvas, so it is hidden. Also the lineglobal screenWidth, screenHeightis not necessary and better be removed. Another suggestion is to inheritTUICanvfromtk.Canvas.self.canvas.pack()