我才刚刚开始学习Python,并且无法使GUI与我的应用程序一起使用。这是我想要的功能:
1)用户在文本框中输入字符串<100个字符
2)程序一次从字符串中切出5个字符,并计算子字符串中字母“ A”和“ B”的数量
3)程序将5个字符的子字符串和每个字母的#打印到GUI文本框
这是我到目前为止所拥有的:
from tkinter import *
from tkinter.ttk import *
class App(Frame):
def __init__(self):
super().__init__()
# Global variables
self.input_text = StringVar
self.output_text = StringVar
self.letter_A = 0
self.letter_B = 0
self.launchGUI()
def launchGUI(self):
self.button_selected_string = StringVar()
self.pack(fill=BOTH, expand=True)
self.topFrame = Frame(self)
self.topFrame.grid(row=0)
self.bottomFrame = Frame(self)
self.bottomFrame.grid(row=2)
# Input textbox
self.input_textbox = Text(self.topFrame, height=5, width=50, borderwidth=2, relief=RIDGE)
self.input_textbox.grid(row=1)
# Output textbox
self.output_textbox = Text(self.bottomFrame, height=5, width=50, borderwidth=2, relief=RIDGE)
self.output_textbox.grid(row=2)
# Submit button
self.submitButton = Button(self.bottomFrame, text="Submit", width=30, command=self.print_result)
self.submitButton.grid(row=1)
# Radio button
self.radioButton1 = Radiobutton(self.bottomFrame, text="Name of Button", variable=self.button_selected_string,
value="BUTTON_SELECTED",
command=self.get_button_state)
self.radioButton1.grid(row=0)
# Function for printing result in textbox
def print_result(self):
self.iterate() # Calls another method
self.output_textbox.insert("1.0", str(self.output_text) + str(self.letter_A) + str(self.letter_B))
# Function that retrieves result of user selection and stores as String
def get_button_state(self):
self.button_selected_string.get()
def iterate(self):
temp = self.input_textbox.get("1.0", "end-1c")
if self.get_button_state() == "BUTTON_SELECTED": # Will always be selected for the purpose of example
i = 100
while i > 20:
temp = temp[(i - 5):i]
self.output_text = self.count_letters(temp)
i = i - 1
return self.output_text
def count_letters(self):
for y in self.output_text:
for x in y:
if x == 'A' or x == 'a':
self.letter_A += 1
elif x == 'B' or x == 'b':
self.letter_B += 1
return self.output_text
def main():
root = Tk()
root.geometry("350x300+300+300")
app = App()
root.mainloop()
if __name__ == '__main__':
main()
问题(在很多情况下,我可以确定)是,当我尝试打印结果时,我没有得到5个字符长的子字符串以及字母“ A”和“ B”的数量的列表得到:
<class 'tkinter.StringVar'>00
似乎我有类型错误,可能是在弄乱变量的范围,但是我不确定如何继续...
任何帮助将不胜感激!