[英]Entry not updating tkinter python
我正在尝试使用 python 模块 tkinter 创建一个带有输入框的 window 来制作一个石头剪刀布游戏。 但是,我每次按下按钮时都在努力让输入框更新为另一个值。
from tkinter import *
import random
root = Tk()
root.geometry('450x350')
root.configure(bg='yellow')
#Global variables
text = []
buttonClicked = False
def changeValue():
global buttonClicked
if buttonClicked:
buttonClicked=False
if not buttonClicked:
buttonClicked=True
def button_command():
global text
text.append(player_entry.get())
player_entry.delete(0, END)
def final_calculation():
cmpt_choice = random.choice([0, 1, 2])
def determine_win(user_choice, cmpt_choice):
return (user_choice + -cmpt_choice) % 3
if text[0] == 'Rock' or text[0] == 'rock':
player_choice = 0
elif text[0] == 'Paper' or text[0] == 'paper':
player_choice = 1
elif text[0] == 'Scissors' or text[0] == 'scissors':
player_choice = 2
else:
player_choice = 3
print('Something went wrong with the input')
if player_choice != 3:
print(determine_win(player_choice, cmpt_choice))
return determine_win(player_choice, cmpt_choice)
#Player
player_label = Label(root, text='Rock / Paper / Scissors')
player_entry = Entry(root, width= 20)
player_button = Button(root, text="Confirm", command=lambda:[button_command(), changeValue(), final_calculation()])
player_entry.pack()
player_label.pack()
player_button.pack()
#Positioning
player_entry.place(x = 100, y = 175, anchor = 'center')
player_label.place(x = 100, y = 140, anchor = 'center')
player_button.place(x= 205 , y = 175, anchor = 'center')
root.mainloop()
我正在努力解决的问题,即如果我将Rock
作为输入(假设计算机响应始终为 0):
然后我的 output 将是0
这是正确的,但是如果我的下一个输入是像dsadsad
这样的随机输入,则所需的 output 将是'Something went wrong with the input'
。 但是,似乎第一个输入已保存并继续使用,因为 output 仍为0
。
另一方面,如果我们从输入dsdasdasd
开始,则 output 将显示: 'Something went wrong with the input'
。 如果我们随后将输入写成rock
,则 output 仍将'Something went wrong with the input'
而不是所需的 output 0
。
任何帮助表示赞赏,
OBS。 这可能不是编程这种形式的程序的最有效方式,但我是编程新手。
你的if
语句有问题。 您总是将用户输入与列表中的第一项进行比较,使用text[0]
,您需要将其更改为text[-1]
以获取附加到列表的最后一项。 所以你的 function 将是:
def final_calculation():
global player_choice
cmpt_choice = random.choice([0, 1, 2])
def determine_win(user_choice, cmpt_choice):
return (user_choice + -cmpt_choice) % 3
if text[-1].lower() == 'rock':
player_choice = 0
elif text[-1].lower() == 'paper':
player_choice = 1
elif text[-1].lower() == 'scissors':
player_choice = 2
else:
player_choice = 3
print('Something went wrong with the input')
if player_choice != 3:
print(determine_win(player_choice, cmpt_choice))
return determine_win(player_choice, cmpt_choice) # Button callbacks have no use returning data
您还可以删除or
将所有文本转换为小写或大写,然后在它们之间进行比较。 我还假设这不是整个代码,因为您的某些函数没有任何真正的目的(还没有?)并且从按钮回调返回也没有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.