为什么我的if语句不导致操作被执行



我正在使用tkinter在python中制作一个简单的石头剪刀布游戏,我正在从条目中获取数据并将其与计算机生成的内容进行比较以执行任务,但是当我输入与随机生成的相同的选择时,它不会在终端中打印'draw',我还没能找到我的代码的任何问题。

import tkinter as tk
from tkinter import *
import random
#make window
root = Tk()
root.geometry('400x300')
possible_actions = ['rock','paper','scisors']
computer_action = random.choice(possible_actions)
print(computer_action)

Label1 = Label(root, text="rock paper or scissors")
Label1.place(x=130 ,y=30)
entry1 = Entry(root, width = 20)
entry1.place(x=130, y =70)
entry1.pack
text1 = entry1.get
def button1_command():
if text1 == 'rock' and computer_action == 'rock':
print('draw')
if text1 == 'scisors' and computer_action == 'scisors':
print('draw')
if text1 == 'paper' and computer_action == 'paper':
print('draw')
root.mainloop()

您需要检测条目文本何时被编辑,然后调用button1_command()函数:

import tkinter as tk
from tkinter import *
import random
#make window
root = Tk()
root.geometry('400x300')
possible_actions = ['rock','paper','scisors']
computer_action = random.choice(possible_actions)
print(computer_action)

Label1 = Label(root, text="rock paper or scissors")
Label1.place(x=130 ,y=30)
entry1 = Entry(root, width = 20)
entry1.place(x=130, y =70)
def button1_command(e):
text1 = entry1.get()
if text1 == 'rock' and computer_action == 'rock':
print('draw')
if text1 == 'scisors' and computer_action == 'scisors':
print('draw')
if text1 == 'paper' and computer_action == 'paper':
print('draw')
entry1.bind("<Return>", button1_command)
root.mainloop()

另外,text1必须是一个在该函数内工作的变量,因为在变量实例化后输入被修改,所以如果它是全局的,它不会更新到正确的值。

解决方案很简单,您需要使用get()而不是get。你也没有调用函数来检查响应…我已经重新创建了你的代码,并添加了一个按钮调用函数时点击。

def button1_command():
text1 = entry1.get()
if text1 == 'rock' and computer_action == 'rock':
print('draw')
if text1 == 'scisors' and computer_action == 'scisors':
print('draw')
if text1 == 'paper' and computer_action == 'paper':
print('draw')
import tkinter as tk
from tkinter import *
import random
#make window
root = Tk()
root.geometry('400x300')
possible_actions = ['rock','paper','scisors']
computer_action = random.choice(possible_actions)
print(computer_action)

Label1 = Label(root, text="rock paper or scissors")
Label1.pack()
entry1 = Entry(root, width = 20)
entry1.place(x=130, y =70)
entry1.pack()
Button(root, text="Check", command=button1_command).pack()
root.mainloop()

还需要在函数内获取text1的值,因为如果在外部执行,它将在创建时存储条目小部件的值(由于用户没有输入任何内容,该值将为空)…

为了简单起见,我使用了pack(),你也可以使用place()

最新更新