首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在函数中使用.get()。Python

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

Stack Overflow用户
提问于 2015-03-16 20:23:36
回答 2查看 93关注 0票数 1
代码语言:javascript
运行
复制
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()并只插入数字,它就能工作。提前感谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-03-16 20:37:35

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

代码语言:javascript
运行
复制
Tkinter.Button(root, text="Convert", command=lambda: Factorer(int(enterA.get()),int(enterB.get()),int(enterC.get())))
票数 2
EN

Stack Overflow用户

发布于 2015-03-16 21:38:15

问题的根源在于,您正在将字符串与整数进行比较,因此无限时间循环永远不会完成。这就是为什么程序必须强制退出的原因。

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

例如:

代码语言:javascript
运行
复制
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)

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29086286

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档