当用户输入无效序列时,我试图重置变量def序列中的参数。否则我得到一个RuntimeError:超出最大递归深度错误,因为存储在def序列中的参数仍然无效。有什么建议?我想在其他地方加上“self.sequence(None)”:但这只是为def序列增加了另一个参数。
from tkinter import *
class AT_content_calculator:
def __init__(self, master):
#initialising various widgets
frame_1 = Frame(master)
frame_1.pack()
self.varoutput_1 = StringVar()
self.label_1 = Label(frame_1, text="Please enter a DNA sequence:")
self.label_1.pack()
self.entry_1 = Entry(frame_1, textvariable=self.sequence)
self.entry_1.pack()
self.output_1 = Label(frame_1, textvariable=self.varoutput_1)
self.output_1.pack()
self.button_1 = Button(frame_1, text="Calculate", command=self.validation_check)
self.button_1.pack()
def sequence(self):
self.dna_sequence = self.entry_1.get()
return self.dna_sequence
def validation_check(self):
#used to validate that self.dna_sequence only contains letters G, C, A, T
valid = 'GCAT'
condition = all(i in valid for i in self.sequence())
if condition:
self.at_calculate()
else:
self.varoutput_1.set("Invalid DNA sequence. Please enter again.")
self.validation_check()
def at_calculate(self):
#used to calculate AT content of string stored in self.dna_sequence
self.dna_sequence = self.entry_1.get()
self.total_bases = len(self.dna_sequence)
self.a_bases = self.dna_sequence.count("A")
self.b_bases = self.dna_sequence.count("T")
self.at_content = "%.2f" % ((self.a_bases + self.b_bases) / self.total_bases)
self.varoutput_1.set("AT content percentage: " + self.at_content)
root = Tk()
root.title("AT content calculator")
root.geometry("320x320")
b = AT_content_calculator(root)
root.mainloop()
答案 0 :(得分:1)
问题与“重置”变量的值无关。问题只是你在不改变被验证的值的情况下反复从内部调用validation_check
,所以自然你最终会出现递归错误。您根本不应该再次调用该方法:您已经显示一条消息,告诉用户验证失败,所以不要做任何事情并等待他们更改值并再次按下按钮。
(无论如何,循环在这里比递归要好得多;但正如我所说,你不需要做任何一种,只需让方法结束。)