使用Tkinter的代码在IDLE中工作但在终端

时间:2018-04-19 17:29:37

标签: python-3.x tkinter terminal

这是我的第一个项目(的一部分)。它使用Tkinter在滚动的文本框中输出文本。我使用了Python 3.6.4和IDLE,它运行得很好,但是当我从终端/ Atom运行它后,我从下拉菜单中选择选项后单击ok它只是关闭而没有错误,而在IDLE中它正确输出文本框中的所有文本。

我想使用Py2app独立创建,但为此需要从终端正确执行代码。

以下是代码中的主要代码段。我只是编写了几个月的代码,所以非常感谢任何详细的帮助。

from tkinter import *
from collections import OrderedDict
from tkinter.scrolledtext import *
from collections import Counter

master = Tk()
master.title("App")
master.geometry("600x665")
master.lift()
master.attributes('-topmost', True)

mvar = IntVar()
mvar1 = IntVar()

var = StringVar(master)
var.set("Asc")
var1 = StringVar(master)
var1.set("Ar")

x = OptionMenu(master, var, "Ar", "Ta", "Ge","Can","Le","Vi","Li","Sc","Sa","Cap","Aq","Pi")
x.grid(column =2,row =1)

x1 = OptionMenu(master, var1, "Ar", "Ta", "Ge","Can","Le","Vi","Li","Sc","Sa","Cap","Aq","Pi")
x1.grid(column =2,row =2)


def redirector(inputStr):
txt.insert(INSERT, inputStr)

sys.stdout.write = redirector     

def ok():
redirector("Thanks for using the app")
master.quit() 


label1 = Label(text="  Welcome to the app",bg="#C2DFFF",font=("Times New Roman",18))
label1.grid(column=0,row=0)
label2 = Label(text="Ma: ",bg="#C2DFFF")
label2.grid(column=0,row=2)

txt = ScrolledText(master, bg="#C2DFFF", width = 97, height= 25, font = "Arial 11")
txt.grid(column = 0, row = 14, columnspan=3)

button = Button(master, text="OK", default ='active',command=ok).grid(column=2,row=11)
button = Button(master, text="Reset", default ='active',command=reset).grid(column=2,row=12)
button = Button(master, text ="Cancel",command = cancel).grid(column=0,row=11)

C1 = Checkbutton(master, state = ACTIVE, variable = mvar)
C1.grid(column = 1, row=2)
C2 = Checkbutton(master, state = ACTIVE, variable = mvar1)
C2.grid(column = 1, row=3)


master.mainloop()

This is how the GUI looks like

1 个答案:

答案 0 :(得分:0)

通常不能重新分配sys.stdout.write - 它通常是内置文件对象的只读属性。执行输出重定向的正确方法是将新对象分配给具有sys.stdout方法的write()

您的代码仅在IDLE中工作,因为IDLE已经用自己的重定向对象替换了内置的sys.stdout,该对象完全可以修改。