У меня есть код, который запрашивает несколько входов через командное окно, а затем рассчитывает некоторые графики как файлы сохранения соответственно. Затем я создал Tkinter GUI с входными данными, поступающими из записи windows. Когда это выполняется, появляется первый график, но когда я закрываю его, код зависает. Я попытался поместить операторы печати вокруг оператора plt.show (). Первый оператор print выполняется явно, а второй - нет. Кажется, что код не будет двигаться дальше от plt.show () при прохождении через tkinter, но отлично работает через командную строку. Итак, я включил интерактивный режим для графика (block = False), и он затем переходит к диалогу ttk saveas. Но когда это закончится, оно снова зависнет. Ничего из этого не происходит через командное окно. Поэтому некоторые настройки между обычной командной строкой python 3.8.1 и tkinter 3.8.1 + отличаются / меняются / я не знаю. Я проверил, чтобы убедиться, что одинаковые значения передаются в функции, которые показывают графики и сохраняют файлы. Любая помощь будет принята с благодарностью.
Файл, который работает из командной строки:
from click import prompt
import grf2d_utils
tchoice = int(prompt("DO you want to generate a random field or analyze one? 1=Generate, 2=analyze. The default is Generate.", type=int, default=1))
if tchoice == 1:
nbins = int(prompt('Enter the desired number of bins to use in the histogram analysis. The default is 20:', type=int, default=20))
grf_x = int(prompt("Enter the integer graph size in the vertical direction. The default is 128:", type=int, default=128)) #first coord is row which is vertical
grf_y = int(prompt("Enter the integer graph size in the horizontal direction. The default is 128:", type=int, default=128)) #second coord is col which is horizontal
xlscale = prompt("Enter the vertical length scale for the variation as a persentage of the graph size. The default is 0.1:", type=float, default=0.1)
ylscale = prompt("Enter the horizontal length scale for the variation as a persentage of the graph size. The default is 0.1:", type=float, default=0.1)
angle = prompt("Enter any rotation about the z-axis in degrees. Positive=CW, Negative=CCW. The default is 0.0:", type=float, default=0.0)
choice = prompt("Choose a covariance function. 1=Gaussian, 2=Exponential, 3=Spherical, 4=Stable, 5=ALL. The default is ALL:", type=int, default=5)
mn = prompt("Enter the mean value of the covariance model. The default is 0.0:", type=float, default=0.0)
variance = prompt("Enter the variance of the covariance model. The default is 1.0:", type=float, default=1.0)
lnchoice = prompt("Would you like to transform the field through a logarithm filter?", default="yes")
exportchoice = str((prompt("Do you want to export the field as a CSV file?", default="yes")))
grf2d_utils.grf_gen2d(nbins,grf_x,grf_y,xlscale,ylscale,angle,choice,mn,variance,lnchoice,exportchoice) # this function works fine here but not below.
Код, вызывающий проблемы:
window = tk.Tk()
window.title('Gaussian Random Field Generation and Analysis')
window.geometry('1150x800')
title_label = tk.Label(window, text = 'Gaussian Random Field Tool', font=(None, 20)).place(x = 380, y = 0)
#---
workdir = cwd()
path = workdir + "\gui_pic.jpg"
img = ImageTk.PhotoImage(Image.open(path))
img_label = tk.Label(window, image = img)
img_label.place(x = 650, y = 290)
#--------------------------------------
btn_gen = tk.Button(window, text='Exit', width = 20, font=8, fg = 'blue',command = sys.exit)
btn_gen.place(x = 450, y = 750)
#--------------------------------------
#for generator placement
startx = 30
xoffset = 430
starty = 190
deltay = 40
#--------------------------------------
tk.Label(window, text='Gaussian Random Field Generator',font=50).place(x = 150, y = 100)
genframe = tk.Frame(window, width=525, height=540, highlightbackground = "black", highlightthickness = 1.0)
genframe.place(x = startx - 10, y = starty -50)
#---
#---
tk.Label(window, text='Characteristic z-direction length (fraction of total graph size):',font=8).place(x = startx, y = starty + 2 * deltay)
zlen_win = tk.Entry(window, width = 10)
zlen_win.insert(0, "0.1")
zlen_win.place(x = startx + xoffset, y = starty + 2 * deltay)
#---
def callback(event):
dim = modeldim_cmb.get()
if dim == '3D':
zlen_win.config(state = 'disabled')
else:
zlen_win.config(state = 'normal')
tk.Label(window, text='Model dimension:',font=8).place(x=startx , y = starty - deltay )
model_dim = ('2D', '3D')
checkdim = tk.StringVar()
modeldim_cmb = ttk.Combobox(window, textvariable = checkdim, state = 'readonly', values = model_dim)
modeldim_cmb.current(0)
modeldim_cmb.place(x = startx + 0.815 * xoffset, y = starty - deltay)
modeldim_cmb.bind('<<ComboboxSelected>>', callback)
#--
tk.Label(window, text='Characteristic vertical length (fraction of total graph size):',font=8).place(x = startx, y = starty)
xlen_win = tk.Entry(window, width = 10)
xlen_win.insert(0, "0.1")
xlen_win.place(x = startx + xoffset, y = starty)
#---
tk.Label(window, text='Characteristic horizontal length (fraction of total graph size):',font=8).place(x = startx, y = starty + deltay)
ylen_win = tk.Entry(window, width = 10)
ylen_win.insert(0, "0.1")
ylen_win.place(x = startx + xoffset, y = starty + deltay)
#--
tk.Label(window, text='Mean(Unitless):',font=8).place(x = startx, y = starty + 3 * deltay)
mean_win = tk.Entry(window, width = 10)
mean_win.insert(0, "0.0")
mean_win.place(x = startx + xoffset, y = starty + 3 * deltay)
#---
tk.Label(window, text='Variance(Unitless):',font=8).place(x=startx, y=starty + 4 * deltay)
var_win = tk.Entry(window, width = 10)
var_win.insert(0, "1.0")
var_win.place(x = startx + xoffset, y = starty + 4 * deltay)
#---
tk.Label(window, text='Number of Histogram Bins:',font=8).place(x = startx, y = starty + 5 * deltay)
num_win = tk.Entry(window, width = 10)
num_win.insert(0, "20")
num_win.place(x = startx + xoffset, y = starty + 5 * deltay)
#---
tk.Label(window, text='Z-Axis Angle to rotate Random Field:',font=8).place(x=startx, y = starty + 6 * deltay)
rotate_win = tk.Entry(window, width = 10)
rotate_win.insert(0, "0.0")
rotate_win.place(x = startx + xoffset, y = starty + 6 * deltay)
#---
tk.Label(window, text='Height of graph size:',font=8).place(x = startx, y = starty + 7 * deltay)
height_win = tk.Entry(window, width = 10)
height_win.insert(0, "128")
height_win.place(x = startx + xoffset, y = starty + 7 * deltay)
#---
tk.Label(window, text='Width of graph size:',font=8).place(x=startx, y = starty + 8 * deltay)
width_win = tk.Entry(window, width = 10)
width_win.insert(0, "128")
width_win.place(x = startx + xoffset, y = starty + 8 * deltay)
#---
tk.Label(window, text='Model type:',font=8).place(x=startx , y = starty + 9 * deltay)
model_choice = ('Gaussian', 'Exponential','Spherical', 'Stable', 'ALL')
model_cmb = ttk.Combobox(window, state = "readonly", values = model_choice)
model_cmb.current(0)
model_cmb.place(x = startx + 0.815 * xoffset, y = starty + 9 * deltay)
#---
logvar = tk.IntVar()
logcheck = tk.Checkbutton(window, text='Log Transform of field',font=8,variable=logvar, onvalue=1, offvalue=0)
logcheck.place(x=startx, y = starty + 10 * deltay)
#---
exportvar = tk.IntVar()
exportcheck = tk.Checkbutton(window, text='Export results to file',font=8,variable=exportvar, onvalue=1, offvalue=0)
exportcheck.place(x=startx, y = starty + 11 * deltay)
#----------------------------------
try:
xlscale = abs(float(xlen_win.get()))
except:
xlscale = 0.1
xlen_win.delete(0,100)
xlen_win.insert(0, "0.1")
try:
ylscale = abs(float(ylen_win.get()))
except:
ylscale = 0.1
ylen_win.select_clear()
ylen_win.insert(0, "0.1")
try:
zlscale = abs(float(zlen_win.get()))
except:
zlscale = 0.1
zlen_win.select_clear()
zlen_win.insert(0, "0.1")
try:
mn =abs(float(mean_win.get()))
except:
mn = 0.0
mean_win.select_clear()
mean_win.insert(0, "0.0")
try:
variance = abs(float(var_win.get()))
except:
variance = 1.0
var_win.select_clear()
var_win.insert(0, "1.0")
try:
nbins = abs(int(num_win.get()))
except:
nbins = max(10,abs(nbins))
num_win.select_clear()
num_win.insert(0, "10")
try:
angle = float(rotate_win.get())
except:
angle = 0.0
rotate_win.select_clear()
rotate_win.insert(0, "0.0")
try:
grf_x = abs(int(height_win.get()))
except:
grf_x = 128
height_win.select_clear()
height_win.insert(0, "128")
try:
grf_y = abs(int(width_win.get()))
except:
grf_y = 128
width_win.select_clear()
width_win.insert(0, "128")
if (logvar.get() == 0):
lnchoice = 'no'
else:
lnchoice='yes'
if (exportvar.get() == 0):
exportchoice = 'no'
else:
exportchoice = 'yes'
choice = int(model_cmb.current()) + 1
#---
def run_gen():
import grf2d_utils
grf2d_utils.grf_gen2d(nbins,grf_x,grf_y,xlscale,\ #this function is where the hanging happens.
ylscale,angle,choice,mn,variance,lnchoice,\
exportchoice)
btn_gen = tk.Button(window, text='Run Gaussian Generator',font=8,fg = 'blue',command = run_gen)
btn_gen.place(x = startx + 0.72 * xoffset, y = starty + 10.2 * deltay)
Фрагмент функции , Он висит на plt.show () после закрытия графика вручную, используя GUI. В противном случае работает нормально:
hist,bin_edges = np.histogram(srf, bins = nbins)
figh, axh = plt.subplots(1, 2, sharex = False, sharey = False)
figh.set_size_inches(12,6)
axh[0].set_title(t)
axh[0].imshow(srf, cmap = 'gray', origin='lower')
axh[1].set_title('Histogram of Covariance Model \n mean = ' + str("%.3f" % xmean) + ', variance = ' + str("%.3f" % xvar))
axh[1].hist(srf, density=1, bins = nbins)
axh[1].bar(bin_edges[:-1], hist, width = xwidth, color='#0504aa',alpha=1.0)
plt.show()
ftypes = ['*.png','*.jpg', 'Image Files']
file = filesavebox(msg=None, title=None, default = cwd() + '\\' + f, filetypes=ftypes)
if file != None:
if path.exists(file):
remove(file)
plt.savefig(file)
plt.close()