首页 > 解决方案 > 文本游戏到 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 时,表示未定义。

标签: pythontkinter

解决方案


这样做是因为click()一旦创建窗口就会调用函数。

为了防止它,您可以使用lambda

myButton = Button(root, text=f"hello {bite}/5", command = lambda: click(hp))

推荐阅读