使用 GUI 按钮定义函数 (Python\Tkinter) 初学者级别(问题:“函数;未定义)

Defining functions with GUI buttons (Python\Tkinter) _beginner level_ (issue: "function; not definded)

目前正在学习 Python class,我正在制作一个猜数游戏。

代码目标:

  1. 用户掷骰子,这决定了他们有多少次尝试猜测 1 到 100 之间的数字
  2. 结果保存在记事本中。

我能够在 shell 中运行猜谜游戏。但是,我正在尝试将游戏转换为 GUI。

当前问题

我已将 tk.Button 分配给 运行 按下时的功能。但是,我收到一个错误消息。

下面的代码;

import random
import tkinter as tk
import time
import sys
window = tk.Tk()
window.title("Shanes Number Guessing Game")
window.geometry("900x500")
diceResult = random.randrange(1,6)
print (diceResult)
tries= 0
correct = 0

   
logo = tk.PhotoImage(file="C:\Python-Tkinter pics\numberguess.png")
photo1 = tk.Label(image=logo)
photo1.image = logo
photo1.pack()

#gui buttons and lables

enterGuessLabel = tk.Label(window, text="enter guess below")
enterGuess =  tk.Entry(window)
diceButton = tk.Button(window, text="roll dice", command=throwDice)
diceResultLabel = tk.Label(window, text="you rolled a: ")


#Number guess code


def throwDice():
    count = diceResult
    while not count == 0:
        input1 = int(input("guess a number 1,10 "))
        randNum1 = random.randrange(1,10)

    if (input1 == randNum1):
        print("correct")
        correct += 1
                
    else:
        print ("incorrect")
        tries += 1
        print (randNum1)
        print (count -1)
        count -= 1
        print ("computer", (tries) ,(userName),(correct))



#GUI pack

enterGuessLabel.pack()
enterGuess.pack()
diceButton.pack()
diceResultLabel.pack()
window.mainpack()

这是输出

    5
name 'throwDice' is not defined
Stack trace:
 >  File "C:\Users\shane\source\repos\ICT30118 CertIII Assessment\ICT30118 CertIII Assessment\ICT30118_CertIII_Assessment.py", line 31, in <module>
 >    diceButton = tk.Button(window, text="roll dice", command=throwDice)
Loaded '__main__'
Loaded 'runpy'

我已将“tk.Button”分配给 运行 命令“掷骰子”。 我已将“def 函数”分配为“throwDice():”

当我 运行 程序时,我收到一个错误,指出“throwDice”未定义

任何帮助将不胜感激。

根据 Stack Overflow 用户“Atlas435”的建议,我只是将 tk.Button 代码行移动到“def 函数”代码下。解释器从上到下读取代码,因此要使 tk.Button(command=xyz) 工作,解释器首先需要读取函数。

代码如下:

def throwDice():
    count = diceResult
    while not count == 0:
        input1 = int(input("guess a number 1,10 "))
        randNum1 = random.randrange(1,10)

    if (input1 == randNum1):
        print("correct")
        correct += 1
                
    else:
        print ("incorrect")
        tries += 1
        print (randNum1)
        print (count -1)
        count -= 1
        print ("computer", (tries) ,(userName),(correct))

diceButton = tk.Button(window, text="roll dice", command=throwDice)

#GUI 
enterGuessLabel = tk.Label(window, text="enter guess below")
enterGuess =  tk.Entry(window)
diceResultLabel = tk.Label(window, text="you rolled a: ")
enterGuessLabel.pack()
enterGuess.pack()
diceButton.pack()
diceResultLabel.pack()

在定义按钮之前先定义 throwDice() 函数

因为python解释器从顶部读取