gpt4 book ai didi

python - Tkinter/Matplotlib 后端冲突导致无限主循环

转载 作者:太空狗 更新时间:2023-10-29 21:43:35 34 4
gpt4 key购买 nike

考虑运行以下代码(请注意,这是演示问题的极其简化的版本):

import matplotlib.pyplot as plot
from tkinter import * #Tkinter if your on python 2

def main():

fig = plot.figure(figsize=(16.8, 8.0))

root = Tk()
w = Label(root, text="Close this and it will hang!")
w.pack()
root.mainloop()

print('Code never reaches this point')

if __name__ == '__main__':
main()

关闭第一个窗口可以正常工作,但关闭第二个窗口会导致代码挂起,因为 root.mainloop() 会导致无限循环。此问题是由调用 fig = plot.figure(figsize=(16.8, 8.0)) 引起的。有谁知道如何在调用 matplotlib.pyplot 后让 root 成功关闭?

最佳答案

import matplotlib
from tkinter import *

def main():

fig = matplotlib.figure.Figure(figsize=(16.8, 8.0))

root = Tk()
w = Label(root, text="Close this and it will not hang!")
w.pack()
root.mainloop()

print('Code *does* reach this point')

if __name__ == '__main__':
main()

Tkinter 窗口中嵌入 matplotlib 图时,请使用 matplotlib.figure.Figure 而不是 plt.Figure

关于python - Tkinter/Matplotlib 后端冲突导致无限主循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17535766/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com