我有一点时间清理这个文字的wigit。我承认我是python及其GUI API的新手,但我已经阅读了文档并尝试了Stack Overflow上的建议无济于事。
我见过很多人建议:self.text.delete(0.0, 'end')
import tkinter
from tkinter import Text
def main():
CalculatorGUI(CalculatorController())
class CalculatorController:
def __init__(self):
self.ans = "0"
def calculate(self, textBox):
value = str("")
try:
inputValue = textBox.replace(",", "").replace(" ", "")
if inputValue[:1] in "-*/+%":
value = str(eval(self.ans + inputValue))[::-1]
else:
value = str(eval(inputValue))[::-1]
return self.makeHumanReadable(value)
except:
return "I cannot math that!"
def makeHumanReadable(self, stringValue):
if "." in stringValue:
decimal = stringValue[:stringValue.index(".")]
integer = stringValue[stringValue.index(".") + 1:]
self.ans = (decimal + "." + (','.join(integer[i:i+3] for i in range(0, len(integer), 3))))[::-1]\
.replace(",", "").replace(" ", "")
print("Current answer is: " + self.ans)
return (decimal + "." + (','.join(integer[i:i+3] for i in range(0, len(integer), 3))))[::-1]
else:
self.ans = ','.join(stringValue[i:i+3] for i in range(0, len(stringValue), 3))[::-1] \
.replace(",", "").replace(" ", "")
return ','.join(stringValue[i:i+3] for i in range(0, len(stringValue), 3))[::-1]
class CalculatorGUI:
def __init__(self, controller):
self.controller = controller
self.root = tkinter.Tk()
self.frame1 = tkinter.Frame(self.root)
self.frame2 = tkinter.Frame(self.frame1)
self.text = BetterText(self.frame1, height=1, borderwidth=0)
self.text.insert(1.0, "Enter a math statement:")
# self.text.delete(0.0, 'end') # If this is not commented out, it deletes
# the text but not when put in the listener
# self.text.clearAll() # Same here
self.text.configure(state="disabled")
self.entry = tkinter.Entry(self.frame2, width = 30)
self.calcButton = tkinter.Button(self.frame2, text="Calculate", \
command=self.calculate)
self.text.pack()
self.entry.pack()
self.calcButton.pack()
self.frame1.pack()
self.frame2.pack()
self.root.mainloop()
def calculate(self):
self.entry.delete(0, "end")
self.text.clearAll() # Does not work
if self.entry.get() != "":
self.text.insert("END", self.controller.calculate(self.entry.get()))
main()
任何想法???使用Python 3.4
编辑:我甚至尝试扩展Text小部件并制作clearAll()方法。它再次在构造函数中工作,但在侦听器中不起作用,并且不会抛出任何错误。可能代码中的其他地方存在问题,我只是看不到它。
class BetterText(Text):
def __init__(self, master=None, cnf={}, **kw):
Text.__init__(self, master, kw)
def clearAll(self):
self.delete(0.0, 'end')
答案 0 :(得分:2)
问题似乎是您正在使用text.configure(state =“disabled”),然后尝试写入窗口小部件。在python中,禁用文本框意味着用户无法编辑它,但这也意味着您不能编辑它。您注释掉的代码工作的原因是它出现在您禁用文本小部件的行之前。在尝试更改文本小部件之前,尝试在clear方法中添加text.configure(state =“normal”),然后在完成后再设置状态。当我尝试时,这似乎解决了这个问题。