ようなクラスは、クラスのオブジェクトで初期化します。オブジェクトとは何ですか?インスタンスです。オブジェクトを使用するには、まずオブジェクトを作成する必要があります。あなたはそれをインスタンス化することでそれを行います、web = web_open3()
。次に、open()
関数を使用できます。
オブジェクトは静的である場合もあります。静的オブジェクトとは、インスタンス化しないオブジェクトです。任意のクラスは、インスタンス化されているかどうかに関係なく、静的な変数と関数を持つことができます。のは、あなたのコードを見てみましょう:
class WebOpen3:
a = "webbrowser.open(www.google.de"
@staticmethod
def open():
WebOpen3.a = webbrowser.open("www.google.de")
test = WebOpen3.open()
とインスタンス例:
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()
左に一つの問題がまだある
# 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()
は、今度は、静的な例を見てみましょう。 test = web.open()
またはtest = WebOpen3.open()
の場合、戻り値はopen()
からtest
にバインドしようとしていますが、この関数は何も返しません。したがって、returnステートメントを追加する必要があります。のは、一例として、インスタンスメソッド/関数を使用してみましょう:
def open(self):
self.a = webbrowser.open("www.google.de")
return self.a
または、代わりに値を返すので、ちょうどストレートフォワード関数を呼び出す:
WebOpen3.open()
または
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
Tkinterウィンドウの場合、ビュー内にボタンを表示するには、次のコードを使用します:
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()
ありがとうございます!私はクラスについてより詳しく説明してくれましたが、問題を解決するためにまだ多くのnoobにちょっとした助けをしてくれました...あなたは私とボタン全体のコードの例を送ることができますか?私はそれを実行するとまだ私はそれを実行すると、ボタンをクリックするだけで、Googleを開きます> – SLake
はい、私は同じクラスを使用する2つまたは3つのボタンを作成したいのですが、何をしようとしているのですか?D) – SLake
@SLake私は、私の答えの一番下を関連情報で更新しました。あなたのプログラムはGoogleを開くと言いました。前に 'webbrowser'を使っていませんでしたが、' open() '関数を呼び出すとこれができますか?私はyoutubeのTkinterに関する良いチュートリアルを見つけることをお勧めします。彼らは私にとって非常に役に立ちました。 – Andreas