我想在两个条目获得相同输入后显示错误消息,并且如果可能不在csv文件中打印这些值。你能帮忙吗?
from tkinter import *
import csv
class App(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.output()
def output(self):
self.playerA = Label(text='state player Name A:').pack()
self.E1 = Entry(root, bd=5)
self.E1.pack()
self.playerB = Label(text='state player Name A:').pack()
self.E2 = Entry(root, bd=5)
self.E2.pack()
self.b = Button(root, text='Submit', command=self.writeToFile)
self.b.pack(side=BOTTOM)
def writeToFile(self):
with open('ttest.csv', 'a') as f:
w=csv.writer(f, quoting=csv.QUOTE_ALL)
w.writerow([self.E1.get()])
if __name__ == "__main__":
root=Tk()
root.title('insert new scores')
root.geometry('200x200')
app=App(master=root)
app.mainloop()
root.mainloop()
答案 0 :(得分:0)
如果两个输入字段中的值相等,您可以创建EntryException
类,raise
:
当两个条目不同时,会在csv文件中写入记录
当它们不同时,会引发EntryException
,并且文件中没有任何内容。
from tkinter import *
import csv
class EntryException(BaseException):
pass
class App(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.output()
def output(self):
self.playerA = Label(text='state player Name A:').pack()
self.E1 = Entry(root, bd=5)
self.E1.pack()
self.playerB = Label(text='state player Name A:').pack()
self.E2 = Entry(root, bd=5)
self.E2.pack()
self.b = Button(root, text='Submit', command=self.writeToFile)
self.b.pack(side=BOTTOM)
def writeToFile(self):
if self.E1.get() == self.E2.get():
raise EntryException
else:
with open('ttest.csv', 'a') as f:
w=csv.writer(f, quoting=csv.QUOTE_ALL)
w.writerow([self.E1.get()])
if __name__ == "__main__":
root=Tk()
root.title('insert new scores')
root.geometry('200x200')
app=App(master=root)
app.mainloop()
root.mainloop()
答案 1 :(得分:0)
如果两个数字相等,您也可以使用消息框显示消息/错误。
from tkinter import messagebox
def writeToFile(self):
if(self.E1.get()==self.E2.get()):
messagebox.showinfo("Message", "Both Values are Equal")
else:
with open('test.csv', 'a') as f:
w=csv.writer(f, quoting=csv.QUOTE_ALL)
w.writerow([self.E1.get()])
答案 2 :(得分:0)
在编写之前,您可以通过writeToFile()函数中的简单检查来执行您想要的操作...
def writeToFile(self):
#start new chunk
from tkinter import messagebox
if self.E1.get() == self.E2.get():
messagebox.showerror('Error Message', "Both Users have the name '{}'".format(self.E1.get()))
return
#end new chunk
with open('ttest.csv', 'a') as f:
w=csv.writer(f, quoting=csv.QUOTE_ALL)
w.writerow([self.E1.get(), self.E2.get()])
# ^^^^^^^^^^^^^^^^
tkinter消息框有一些简单的对话框消息选项:
showerror()
,showwarning()
和showinfo()
。与他们一起玩,并选择一个给你的外观和感觉。此外,我还包括将第二个用户名写入CSV文件(如果它们不相同),以防您忽略它。