1

我该如何做到这一点,如果有人输入一个高于 3000 的数字,它会打印出一条自定义消息,而不是计算该特定数字的阶乘?

我试过'如果数字> 3000,打印“blah blah blah”',但它不起作用。认为它与tkinter有关。

from Tkinter import *
import tkMessageBox, os

#calculates factorial of inputNumber
def calculate():
    number = inputNumber.get()
    inputNumber.delete(0, END)
    product = 1
    for i in range(int(number)):
        product = product * (i+1)
    facAnswer.delete(1.0, END)
    facAnswer.insert(END, product)

cal = Tk()
cal.title("Factorial Calculator")
cal.geometry('450x300+200+200')

#Enter the number you want the factorial of 
factorialNumber = IntVar()
inputNumber = Entry(cal, textvariable=factorialNumber)
inputNumber.pack()

#executes calculate function by pressing button
enterButton= Button(cal, text="CALCULATE!", width=20,command=calculate)
enterButton.pack(side='bottom',padx=15,pady=15)

#Where the answer appears:
facAnswer = Text(cal)
facAnswer.insert(END, "Answer:")
facAnswer.pack()

cal.mainloop()
4

1 回答 1

0

It seemed to work for me. You could put everything in a class,
and try using get() on factorialNumber, to see if it makes a difference.

import Tkinter as tk

class GUI(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        self.title("Factorial Calculator")
        self.geometry('450x300+200+200')

    # Enter the number you want the factorial of
        self.factorialNumber = tk.IntVar()
        self.inputNumber = tk.Entry(self, textvariable=
                                    self.factorialNumber)
        self.inputNumber.pack()

    # executes calculate function by pressing button
        enterButton= tk.Button(self, text="CALCULATE!",
                                width=20,command=self.calculate)
        enterButton.pack(side='bottom',padx=15,pady=15)

    # Where the answer appears
        self.facAnswer = tk.Text(self)
        self.facAnswer.insert('end', "Answer:")
        self.facAnswer.pack()


    def calculate(self):
        number = self.factorialNumber.get()
        if number > 3000:
            print('The number is out of range.')
        else:
            self.inputNumber.delete(0, 'end')
            product = 1
            for i in range(int(number)):
                product = product * (i+1)
            self.facAnswer.delete(1.0, 'end')
            self.facAnswer.insert('end', product)


gui = GUI()
gui.mainloop()
于 2012-04-11T05:28:50.143 回答