python - 文本游戏到 Tkinter GUI
问题描述
我正在尝试为我的文本游戏制作 GUI(类似于 pokemom 游戏)
总之,代码的工作方式如下:
import random
hp = 100
for i in range (0,4):
element = input("Enter attack: ")
list.append(element)
attack1 = list[0]
attack2 = list[1]
attack3 = list[2]
attack4 = list[3]
while(True):
cmd = input(">")
If cmd.lower() == attack1 ... :
if cmd.lower() == bite:
hp -= 10
现在我尝试通过按钮在 Tkinter 上做一个 gui,但似乎我无法掌握它
from tkinter import *
#4 buttons
bite = 0
root = Tk()
def click(hp):
hp -= 10
myLabel = Label(text=f"{hp} hp remaining left.")
myLabel.grid(row = 5, column = 5)
def click2():
bite = 0
hp = 50
hp -= 20
myLabel = Label(text=f"{hp} hp remaining left.")
myLabel.grid(row = 5, column = 5)
bite += 1
myButton = Button(root, text=f"hello {bite}/5", command = click(hp))
myButton2 = Button(root, text=f"Presssss {bite}/5", command = click2)
myButton3 = Button(root, text="Presssss")
myButton4 = Button(root, text="Presssss")
myButton.grid(row = 0, column = 1)
myButton2.grid(row = 1, column = 1)
myButton3.grid(row = 1, column = 2)
myButton4.grid(row = 0, column = 2)
root.mainloop()
由于函数中包含变量,这只是呈现一个常量值“90, 30”,但是每当我试图将它放入一个参数中时
hp = 100
def click(hp):
hp -= 10
button1 = Button(root, text = "try", command = click(100))
它只是在单击按钮之前返回值 90、30。当 hp 用作 arg 时,表示未定义。
解决方案
这样做是因为click()
一旦创建窗口就会调用函数。
为了防止它,您可以使用lambda
:
myButton = Button(root, text=f"hello {bite}/5", command = lambda: click(hp))
推荐阅读
- c++ - 找不到“boost_atomic”提供的包配置文件
- c - 如何在不杀死进程的情况下使用 LD_PRELOAD
- javascript - Javascript多值对象到简单数组
- angular - 角度延迟加载模块重新加载不起作用
- create-react-app - 如何在 node-sass .scss 文件中使用环境变量?
- java - Gmail API for JAVA - Eclipse 项目 - 阅读新邮件和下载附件
- database - How to restrict files in a database/table to certain users logged into wix website
- docker - 在 fluent-bit docker 容器中获得权限被拒绝
- c++ - `boost::serialization::load_construct_data` 的实现抛出内存访问冲突错误
- django - 在 django 模型中继承具有单独主键的模型