Tkinter中的字符串比较

时间:2017-12-13 14:59:19

标签: python string tkinter

我正在尝试编写简单的GUI来生成数字,将它们写入字符串,按“Check”按钮后,它会将用户的输入与生成的数字进行比较。在此代码函数中print(x==y)应该打印我是真的,因为我提供了生成的相同数字,但它打印我FALSE。问题是什么?你能帮帮我吗?

from tkinter import*
from random import randint

def compare():
    global string2
    global string1

    string2=str(string2.get())
    print (string1 == string2)




def generate():
    global k
    number.config(text=string1[k])
    k=k+1
    number.after(2000, remove) 

def remove():
    global repeat

    number.config(text='')

    repeat -= 1
    if repeat > 0:
        number.after(1000, generate) 



root = Tk()

i=3
k=0
j=0
repeat = i
string1=str()
string2=StringVar()

while j < i:
    string1=string1+str(randint(1,10))
    j=j+1



number = Label(root, width=20, height=10)
number.pack()

ent = Entry(root,width=20,bd=3)
ent.pack()

but = Button(text="Check",command = compare)
but.pack()


generate()

root.mainloop()

1 个答案:

答案 0 :(得分:0)

主要问题是ranint(1,10),可以提供值1...10,而不是1...9
  所以最后它产生4位数字而不是3位数字 (但它甚至可以生成6位数字"101010" - "10" + "10" + "10"

使用randint(1, 9)randrange(1, 10)

import tkinter as tk
from random import randint

# --- functions ---

def compare():
    print(number_str == answer.get())

def generate():
    global index

    lab.config(text=number_str[index])

    index += 1

    root.after(2000, remove) 

def remove():
    global repeat

    lab.config(text='')

    repeat -= 1
    if repeat > 0:
        root.after(1000, generate) 

# --- main ---

number_of_digits = 3
repeat = number_of_digits

index = 0

number_str = ""

for _ in range(number_of_digits):
    number_str = number_str + str(randint(1,9))

#print(number_str)

root = tk.Tk()

answer = tk.StringVar()

lab = tk.Label(root, width=20, height=10)
lab.pack()

ent = tk.Entry(root, textvariable=answer, width=20, bd=3)
ent.pack()

but = tk.Button(text="Check", command=compare)
but.pack()

generate()

root.mainloop()