如何在Python函数中使用.get()

2024-09-30 05:17:34 发布

您现在位置:Python中文网/ 问答频道 /正文

from Tkinter import *
import random

def Factorer(a,b,c):
    while True:
        random_a1=random.randint(-10,10)
        random_a2=random.randint(-10,10)
        random_c1=random.randint(-10,10)
        random_c2=random.randint(-10,10)
        if random_a1==0 or random_a2 == 0 or random_c1 == 0 or random_c2 == 0:
            pass
        elif (random_a1*random_c2) + (random_a2*random_c1) == b and random_a1/random_c1 != random_a2/random_c2 and random_a1*random_a2==a and random_c1*random_c2==c:
            break
    print "y=(%dx+(%d))(%dx+(%d))" % (random_a1,random_c1,random_a2,random_c2)

root = Tk()
buttonSim1 = Button(root, text="Convert", command=lambda: Factorer(enterA.get(),enterB.get(),enterC.get()))
buttonSim1.grid(row=2, column=3)
enterA = Entry(root)
enterA.grid(row=1, column=1)
enterB = Entry(root)
enterB.grid(row=1, column=2)
enterC = Entry(root)
enterC.grid(row=1, column=3)

root.mainloop()

我怎么才能让这个代码运行,每次我点击按钮它只是崩溃。 但是,如果我删除.get()并只插入数字,它就可以工作了。 提前谢谢


Tags: oranda2geta1columnrandomroot
2条回答

如果要将字符串与int进行比较,则需要将a,bc转换为int:

Tkinter.Button(root, text="Convert", command=lambda: Factorer(int(enterA.get()),int(enterB.get()),int(enterC.get())))

问题的根源在于,您将字符串与整数进行比较,因此您的无限while循环永远不会结束。这就是为什么该计划的手,并不得不被迫退出。你知道吗

最好的解决方案是让您的按钮调用一个函数来获取数据,将其格式化为适当的值,然后调用该函数来完成工作。试图将所有这些压缩到一个lambda中会导致一个很难调试的程序。你知道吗

例如:

def on_button_click():
    a = int(enterA.get())
    b = int(enterB.get())
    c = int(enterC.get())

    result = Factorer(a,b,c)
    print(result)

Tkinter.Button(..., command=on_button_click)

通过使用单独的函数,您可以添加打印语句或pdb断点,以便在数据运行时检查数据。它还使添加try/catch块更容易处理用户没有输入有效数字的情况。你知道吗

相关问题 更多 >

    热门问题