使用するキーワードがわからないため、これらの問題を検索できませんでした。重複している場合や他の場所で回答されている場合は、お知らせください。
tkinterでメインウィンドウを作成し、異なる関数とクラスを持つ他のモジュールをインポートするファイルがあります。クラスのメソッドで、作成したtkinterウィジェットに何かを出力したいと思います。どうすればいいですか?
file1.py:
from tkinter import * # I use python 3
import tkinter.scrolledtext as tkst
from file2 import *
class Application(Frame):
def __init__(self, master):
super(Application, self).__init__(master)
self.output_text = tkst.ScrolledText(self, width = 100, height = 20,
wrap = WORD, bd=0)
self.output_text.grid(row = 9, column = 0, columnspan = 5, sticky="nsew")
root = Tk()
root.title("Game")
app = Application(root)
center(root)
root.mainloop()
file2.py:
class Hero(object):
def attack(self, enemy, damage):
Hero.hits+=1
if self.hits==0:
attack = "{}, attacks our enemy {}. Producing {} points of damage.\n".format(
self.__name, enemy.creature, truncate(damage))
# I use code like this in the Application definition.
app.output_text.insert(END, attack)
しかし、それは次のようになりました。
File "C:\....\file2.py", line 112, in attack
app.output_text.insert(END, attack)
NameError: global name 'app' is not defined
あるモジュールを別のモジュールに関連付ける必要があると思いますが、方法がわかりません(super
関数については読みましたが、ここでは使用方法がわかりません)。そのようなことをするか、ヒーローとアプリケーションの間で情報を渡すためのイベントを作成する必要がありますか?
クラスHero
をにインポートし、アプリを別の引数として渡すことでfile1.py
関数を呼び出すことができattack
ます
注:敵とダメージが何であるかわからないので、あなたのためにそれをスキップしています
from tkinter import * # I use python 3
import tkinter.scrolledtext as tkst
from file2 import *
from file2 import Hero#importing the oth
class Application(Frame):
def __init__(self, master):
super(Application, self).__init__(master)
self.output_text = tkst.ScrolledText(self, width = 100, height = 20,
wrap = WORD, bd=0)
self.output_text.grid(row = 9, column = 0, columnspan = 5, sticky="nsew")
root = Tk()
root.title("Game")
app = Application(root)
center(root)
h = Hero()
h.attack(enemy, damage, app) #passing as third argument)
root.mainloop()
file2.py
class Hero(object):
def attack(self, enemy, damage,app): #change the defenition
Hero.hits+=1
if self.hits==0:
attack = "{}, attacks our enemy {}. Producing {} points of damage.\n".format(
self.__name, enemy.creature, truncate(damage))
# I use code like this in the Application definition.
app.output_text.insert(END, attack)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加