0

これは、ボタンの配列が相互に影響し合うための初期コードにすぎません。なぜこの定義エラーが発生し続けるのか理解できません!

from tkinter import *
import tkinter.messagebox
from tkinter import ttk


def changeImage(Num):
    global buttonOn
    global buttonOff
    if Num == 1:
        if button1(image) == buttonOn:
            button1.config(image=buttonOff)
        else:
            button1.config(image=buttonOn)

root = Tk()

root.geometry('155x190')
root.title("Tile Turner")

buttonOn = PhotoImage(file="buttonPic.gif")
buttonOff = PhotoImage(file="buttonPic2.gif")

button1 = Button(image=buttonOn, width=20, height=20, command=changeImage(1))
buttonQuit = Button(text="Quit", width=10, height=0, command=root.destroy)


app.grid(column=0, row=0)
button1.grid(column=2, row = 3)
buttonQuit.grid(column=3, row = 10, columnspan = 4)

root.mainloop()

私の定義エラーはbutton1にあります。

Traceback (most recent call last):
  File "C:/Users/Jimmy/Desktop/COS 2013/Game1/small", line 23, in <module>
    button1 = Button(image=buttonOn, width=20, height=20, command=changeImage(1))
  File "C:/Users/Jimmy/Desktop/COS 2013/Game1/small", line 10, in changeImage
    if button1(image) == buttonOn:
NameError: global name 'button1' is not defined

どんな助けでもいただければ幸いです!

4

3 に答える 3

1

この行では、

button1 = Button(image=buttonOn, width=20, height=20, command=changeImage(1))

changeImage引数として渡す関数を呼び出し1ます。次に、その関数が評価され、結果(この場合)がコンストラクターのデフォルト引数にNone渡されます。もちろん、これにより、実際にButtonコンストラクターに渡す前に呼び出すために取得できます。つまり、インスタンスの構築を続行する前に関数が終了するのを待っているため、まだ存在していません。command=...ButtonNameErrorchangeImagebutton1changeImageButton

あなたは次のようなものが欲しいです:

button1 = Button(...,command=lambda:changeImage(1))

changeImageこれにより、呼び出されたときに適切な引数を指定して呼び出す新しい関数が作成されます。

ラムダについてもう少し詳しく説明すると、上記のステートメントは多かれ少なかれ省略形です。

def temp_function():
    return changeImage(1)

button1 = Button(...,command=temp_function)
于 2013-03-01T02:48:40.683 に答える
0

button1あなたの上に(そして他のものを)宣言してみてくださいdef changeImage(Num)。Python はトップダウンで読み取るため、関数が呼び出されていなくても、その時点に到達する前にすべてを宣言する必要があります。

于 2013-03-01T02:39:12.097 に答える
0

イベントハンドラーで切り替えることができるように、画像への参照を保持する必要があります。

def changeImage(num):
    global buttonOn, buttonOff, button1
    if num == 1:
        newimage = buttonOff if button1.image == buttonOn else buttonOn
        button1.image = newimage
        button1.config(image=newimage)

# ...
button1 = Button(image=buttonOn, width=20, height=20, command=lambda:changeImage(1))
button1.image = buttonOn
于 2013-03-01T02:56:25.450 に答える