Skip to main content
 首页 » 编程设计

python之如何从 python 的 tkinter Canvas 中删除空白

2024年10月24日8yxwkf

我尝试在 Internet 上搜索很多解决方案,但没有找到任何解决方案。我正在尝试移除 Canvas 上绘图周围的空白区域,如图所示,但到目前为止我没有成功。

我写的简单代码是:

import tkinter as tk 
import matplotlib 
from matplotlib import style 
style.use('seaborn-darkgrid') 
matplotlib.use("TkAgg") 
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,    NavigationToolbar2TkAgg 
from matplotlib.figure import Figure 
import random 
 
class GUIplot(tk.Tk): 
    def __init__(self, *args, **kwargs): 
        tk.Tk.__init__(self, *args, **kwargs) 
        printButton = tk.Button(self, text="Plot1", command=lambda: self.printMessage(canvas,a)) 
        printButton.grid(row=0, column=0, sticky='w')  
        f = Figure(figsize=(24,12)) 
        a = f.add_subplot(111, axisbg='r') 
        canvas = FigureCanvasTkAgg(f, self) 
        canvas.get_tk_widget().grid(row=1, columnspan=2) 
        #canvas._tkcanvas.config(bg='blue') 
        canvas.show() 
        canvas.blit()         
 
    def printMessage(self,canvas,a): 
        a.clear() 
        my_random_x = random.sample(range(100),10) 
        my_random_y = random.sample(range(100),10) 
        a.plot(my_random_x,my_random_y,'*') 
        canvas.draw() 
        print("Wow") 
 
GUIplot1 = GUIplot() 
GUIplot1.title('PlotFunction') 
w, h = GUIplot1.winfo_screenwidth(), GUIplot1.winfo_screenheight() 
GUIplot1.geometry("%dx%d+0+0" % (w, h)) 
GUIplot1.mainloop() 

Attached Image

如果社区中的任何成员对如何解决此问题有任何想法,请给我提供一些指导。

请您参考如下方法:

我与 FigureCanvasTkAgg 无关,但只要它基于 tk.Canvas,它就可以工作:

在 tk.Canvas 中你只需使用

canv=tk.Canvas(master=root, bd=0, highlightthickness=0) 

尝试将以下参数添加到 FigureCanvasTkAgg 调用:bd、highlightthickness。

希望我有所帮助!