In programming, a class is an object. What is an object? It's an instance. In order to use your object, you first have to create it. You do that by instantiating it, web = web_open3()
. Then, you can use the open()
function.
Now, objects may also be static. A static object, is an object that you don't instantiate. Any class, independent of being instantiated or not, may have static variables and functions. Let's take a look at your code:
# Classes should be named with CamelCase convention: 'WebOpen3'
class web_open3:
# This is a static variable. Variables should be named with lowercase letters
A = "webbrowser.open(www.google.de"
# This is an instance method
def open(self):
# You are accessing a static variable as an instance variable
self.A = webbrowser.open("www.google.de")
# Here, you try to use an instance method without first initializing your object. That raises an error, the one you gave in the description.
test = web_open3.open()
Let's now look at a static example:
class WebOpen3:
a = "webbrowser.open(www.google.de"
@staticmethod
def open():
WebOpen3.a = webbrowser.open("www.google.de")
test = WebOpen3.open()
and an instance example:
class WebOpen3:
def __init__(self):
self.a = "webbrowser.open(www.google.de"
def open(self):
self.a = webbrowser.open("www.google.de")
web = WebOpen3()
test = web.open()
There is still one problem left. When saying:
test = web.open()
, or test = WebOpen3.open()
, you're trying to bind the returning value from open()
to test
, however that function doesn't return anything. So, you need to add a return statement to it. Let's use the instance method/function as an example:
def open(self):
self.a = webbrowser.open("www.google.de")
return self.a
or, instead of returning a value, just call the function straight-forward:
WebOpen3.open()
or
web.open()
Note: functions belonging to instances, are also called methods.
Note: self
refers to an instance of that class.
Note: def __init__(self)
, is an instance´s initializer. For your case, you call it by using WebOpen3()
. You will later find more special functions defined as def __func_name__()
.
Note: For more on variables in a class, you should read this: Static class variables in Python
As for the case of your Tkinter window, to get a button in your view: you can use this code:
from tkinter import *
app = Tk()
button = Button(app, text='Open in browser')
button.bind("<Button-1>", web.open) # Using 'web.open', or 'WebOpen3.open', both without parenthesis, will send a reference to your function.
button.pack()
app.mainloop()