Reputation: 135
How do i access windows function in Mygui class? I want to create colored content in my tkinter box# but i can't pass value to it.
from tkinter import *
class Mygui:
def window(self, colour):
self.main_window=Tk()
self.main_window.geometry('300x100')
self.main_window.title('Login')
self.top_frame=Frame(self.main_window)
self.top_frame.pack()
self.label=Label(self.top_frame, fg=colour, text="Sample Text", width=45)
self.label.pack(side="top")
self.label1=Label(self.top_frame,text=" ", width=45)
self.label1.pack(side="top")
self.my_button = Button(self.main_window, text="Retry", command=self.do_something, height=2, width=18)
self.my_button.pack()
mainloop()
def do_something(self):
print('ok')
class login:
def example(self):
print("Start")
Mygui.window('blue')
a = login.example(' ')
The error i get is:
Start
Traceback (most recent call last):
File "B:/data/loginMech/test.py", line 25, in <module>
a = login.example(' ')
File "B:/data/loginMech/test.py", line 23, in example
Mygui.window('blue')
TypeError: window() missing 1 required positional argument: 'colour'
Upvotes: 2
Views: 295
Reputation: 15226
Abarnet pointed out one fix however in Tkinter it might be better to inherit from the Tkinter class Tk
to start you GUI.
Take this example. A much smaller amount of code and produces the same results desired.
import tkinter as tk
class MyGUI(tk.Tk):
def __init__(self, colour):
tk.Tk.__init__(self)
self.geometry('300x100')
self.title('Login')
tk.Label(self, fg=colour, text="Sample Text", width=45, pady=10).grid(row=0, column=0)
tk.Button(self, text="Retry", command=self.do_something, height=2, width=18).grid(row=1, column=0)
def do_something(self):
print('ok')
MyGUI("Blue").mainloop()
Results:
Upvotes: 1
Reputation: 365787
Mygui
is a class, not a function. So, you have to construct an instance of it, like this:
gui = Mygui()
And then you can call methods on that instance:
gui.window('blue')
When you write Mygui.window
, that's an unbound method, which you can call by explicitly passing it a self
argument along with its other arguments. But you'd still need to have something to pass as that self
:
gui = Mygui()
Mygui.window(gui, 'blue')
In general, you don't want to do this. There are cases where unbound methods are useful, but if you have one, you probably know you have one.
And you need to do the same thing with login
:
log = login()
log.example()
By calling login.example
, you're using an unbound method again. And then you're passing ' '
as the self
argument. This doesn't make any sense, because ' '
is not a login
instance, but CPython 3.x happens to not check for that error, so you get away with it.
Upvotes: 2