无法使用Tkinter获得所需的界面

时间:2014-05-26 07:53:55

标签: python tkinter

我一直致力于一个小型项目,其中计算器必须嵌入盒子中。我正在使用 Tkinter

我的代码:

import tkinter

top = tkinter.Tk()

def add(x, y):
  return x + y

def subtract(x, y):
  return x - y

def multiply(x, y):
  return x * y

def divide(x, y):
  return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if choice == '1':
  print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
  print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
  print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
  print(num1,"/",num2,"=", divide(num1,num2))
else:
  print("Invalid input")

top.mainloop()

问题是计算器没有在包装盒内打开。我得到以下输出:

Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15 * 14 = 210

我需要的是在盒子里面显示它。

1 个答案:

答案 0 :(得分:0)

你还没有创建一个“盒子”,所以在你做之前显示一个东西会很困难。

该行:

top = tkinter.Tk()

Tkinter GUI创建根窗口。要在其中打印内容,您需要添加可在根窗口中写入的窗口小部件(GUI元素)。这里一个很好的选择是Text小部件:

import Tkinter as tk

root = tk.Tk()
my_text = tk.Text(root)
my_text.pack()

现在要打印到文本框而不是终端,您可以用Text.insert方法替换打印语句。

my_text.insert(tk.END,"Hello, this is some text\n")
my_text.insert(tk.END,"This is some other text\n")
my_text.insert("0.0","This is some text starting at row 0 and column 0\n")
my_text.insert(tk.CURRENT,"This is even more text, this time starting from the current cursor position\n")