在 Tkinter GUI 中,我有三个 Entry 小部件,用于将数字输入到嵌套的 for 循环中,该循环创建一个数组,用于在点击“提交”按钮后创建 seaborn 热图。 Entry 小部件位于框架中,我想在框架下方的 GUI 窗口中绘制热图。我可以创建绘图轴,但热图不显示。任何建议将不胜感激。
`import random
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.backend_bases import key_press_handler
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from tkinter import*
root = Tk()
def HPS(x,y,z): #HPS Function
NUMX = int(x.get()) # No. of columns (x)
NUMY = int(y.get()) # No. rows (y)
NUMZ = int(z.get())# No. of levels (z)
z = np.zeros((NUMZ)) # define number of levels
conc = np.zeros((NUMZ, NUMY, NUMX)) #Create 3d conc array (z,y,x)
for z in range(NUMZ):
for y in range(NUMY):
for x in range(NUMX):
c = round(random.uniform(0.0, 1.0) ,2)
conc[z,y,x] = c # fill array with for loops
conc_sum = conc.sum(axis=0) # add the two z-levels together
print(conc_sum)
df_sum = pd.DataFrame(conc_sum) # Create dataframe of sum_conc array
#Create heatmap and plot in Tkinter
figure = Figure(figsize=(4, 4))
ax = figure.subplots()
sns.heatmap(df_sum,cmap='RdBu') # Create heatmap
plt.ylim(0,NUMY) # Reverse y-axis coordinates
# Plot heatmap in Tkinter
canvas = FigureCanvasTkAgg(figure, master=root)
canvas.draw()
canvas.get_tk_widget().grid(row =8, column=0, columnspan=3)
# HPS Tkinter GUI
root.geometry("400x400") # Set sizeof GUI
frame1 = Frame(root) #Create fame for input boxes
frame1=LabelFrame(root, text='Frame 1', padx=10, pady=10)
frame1.grid(row=0, column=0)
#Create input boxes and labels
label1 = Label(frame1, text='NUMX = ')
label1.grid(row=0, column=0)
label2 = Label(frame1, text='NUMY = ')
label2.grid(row=1, column=0)
label3 = Label(frame1, text='NUMZ = ')
label3.grid(row=2, column=0)
#Enter data
x = Entry(frame1)
y = Entry(frame1)
z = Entry(frame1)
x.grid(row=0, column = 2)
y.grid(row=1, column = 2)
z.grid(row=2, column = 2)
#Create submit button and call HPS function
myButton = Button(root, text='Submit', command = lambda:HPS(x,y,z))
myButton.grid(row = 5, column = 2)
root.mainloop()`
我按照不同论坛的建议尝试了各种不同的 Tkinter 代码来显示绘图
HPS 函数中的以下代码更改创建了热图
'#Create heatmap and plot in Tkinter
figure = Figure(figsize=(4, 4))
ax = figure.add_subplot(111)
sns.heatmap(df_sum,ax=ax,cmap='RdBu') # Create heatmap
plt.ylim(0,NUMY) # Reverse y-axis coordinates
canvas = FigureCanvasTkAgg(figure, master=root)
canvas.draw()
canvas.get_tk_widget().grid(row =8, column=0, columnspan=3)'