【发布时间】:2020-11-28 12:46:28
【问题描述】:
目前正在学习Python上课,我正在创建一个猜数字游戏。
代码目标:
- 用户掷骰子,这决定了他们尝试猜测 1 到 100 之间的数字的次数
- 结果保存在记事本中。
我能够让猜谜游戏在 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”未定义的错误
任何帮助将不胜感激。
【问题讨论】:
-
您需要先定义您的函数,然后才能将其用作命令。通常你在导入你的东西后立即定义你的全局函数。请记住,您的解释器会从左到右和从上到下读取您的代码。
-
我不确定如何定义同名函数,我尝试使用全局函数。将在主帖中发布结果。
-
我知道我把你弄糊涂了。我所说的全局函数的意思是你的函数在全局命名空间中。你不需要定义这个函数两次,你需要把它放在正确的位置。您的解释器再次从上到下读取您的代码。您的函数位于代码的最底部,而您的按钮位于中间。此时您的口译员应该如何知道您的功能?全局命名空间链接medium.com/@gough.cory/…
-
成功了,我会编辑帖子,谢谢。