我在Tkinter GUI中为Collatz猜想编写了一个脚本,并显示了算法结果的Matplotlib图。一切正常,除了该图可以完美显示,但随后在不填充显示该图所基于的数据点的数据字段的情况下停止了脚本。仅当我关闭图形时,才会填充数据字段。
我确定我在脚本中做错了一些事情(可能是缩进),但是我已经尝试了所有方法,但无法使其正常工作。该脚本添加如下:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tkinter import *
from tkinter import messagebox
root=Tk()
root.title("Collatz Conjecture")
import matplotlib.pyplot as plt
import textwrap
from IPython import get_ipython
# sget_ipython().run_line_magic('matplotlib', 'qt')
#import matplotlib.backends.tkagg as tkagg
#from matplotlib.backends.backend_agg import FigureCanvasAgg
# Functions
lst = []
def collatz(num):
lst.clear()
while num != 1:
lst.append(num)
if num % 2 == 0:
num = int(num / 2)
else:
num = int(3 * num + 1)
def main(event):
num = int(input.get())
collatz(num)
plt.plot(lst)
plt.show()
output1.delete(1.0, END)
output1.insert(END, lst)
output2.delete(1.0, END)
output2.insert(END, "Number of iterations: " + str(len(lst)))
lbl1 = Label(root, width = 20, text = "Type in number\n & press Enter")
lbl1.grid(row = 1, column = 0, sticky = W)
lbl2 = Label(root, width = 40, text = "THE COLLATZ CONJECTURE")
lbl2.grid(row = 4, column = 0)
input = Entry(root, width = 20, bg = "light grey")
input.grid(row = 1, padx = 6, sticky = E)
input.get()
input.bind("<Return>", main)
canv = Canvas(root, width= 350, height= 350, bg = "white")
canv.grid(row = 6, column = 0, padx = (5,5), pady = (5,5))
img = PhotoImage(file = "/Users/andrehuman/Desktop/collatz_conjecture.png") # Tip to get full path: pull file into terminal!
canv.create_image(25, 25, image = img, anchor = NW)
bt1 = Button(root, width = 10, text = "About")
bt1.grid(row = 7, column = 0, pady = (5,7))
output1 = Text(root, wrap = WORD, width = 50, height = 7, bg = "light grey") # Note word wrap attribute
output1.grid(row = 3, column = 0, padx = (5,1), sticky = W)
output2 = Text(root, width = 50, height = 1, bg = "white")
output2.grid(row = 2, column = 0, sticky = W)
def about():
messagebox.showinfo("About", "The Collatz conjecture states that if you pick any positive whole number, and if its even, you divide it by two and if its odd, you multiply it by three and add one, and if you repeat this procedure often enough, the number that you started with will eventually reduce to one and if you play this game for long enough, your friends will eventually stop calling to see if you want to hang out ")
btn1 = Button(root, text = "About", command = about)
btn1.grid(row = 7, column = 0, pady = (5,7))
root.mainloop()
任何帮助将不胜感激。
安德烈
PS,我不是专业的编码员,也不是学生编码员。。。我只是出于爱好,并向自己介绍编码。