[英]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.