如何将绘制的图形放置在tkinter风的特定位置

2024-09-28 03:21:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python编程新手,我面临的问题是,在绘制图形时,我无法将图形放置在所需的位置。我可以使用tkinter的place()方法在tkinter窗口中的任意位置放置按钮。你知道吗

这是我的家庭项目。在下面的代码中,我做了两个按钮,其中“连接”按钮将连接到arduino,plot按钮将从arduino获取数据并进行绘图,因为这是一个测试代码,所以我在其中输入了随机值。你知道吗

### Author = Peouse Dutta

import tkinter as tk
from tkinter import ttk
import serial
import serial.tools.list_ports
import time
import matplotlib
matplotlib.use('TkAgg')

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt


root = tk.Tk()
root.title("ANALYSER")
root.geometry("1000x700")
root.configure(background = 'white')


def get_ports():
    ports = serial.tools.list_ports.comports()
    return ports

def findArduino(portsFound):
    commPort = 'None'
    numConnection = len(portsFound)

    for i in range(0,numConnection):
        port = portsFound[i]
        strPort = str(port)

        if 'Arduino' in strPort:
            splitPort = strPort.split(' ')
            commPort = (splitPort[0])

    return commPort


class AppWindow(tk.Tk):
    def __init__(self, window):
        self.window = window
        self.connect = ttk.Button(window, text = "CONNECT", command = self.Connect)
        self.connect.pack()
        self.getValue = ttk.Button(window, text = "PLOT", command = self.plot)
        self.getValue.pack()


    def Connect(self):
        self.FoundPorts = get_ports()
        self.connectPort = findArduino(self.FoundPorts)
        if self.connectPort != 'None':
            ser = serial.Serial(self.connectPort, baudrate = 9600)
            #time.sleep(1.5)
            print('Connected to ' + self.connectPort)
            tk.messagebox.showinfo('STATUS', 'CONNECTED')
        else:
            print('Connection Issue!')
            tk.messagebox.showinfo('STATUS', 'NOT CONNECTED!')

    def plot(self):
        fig = plt.figure(figsize = (10,2), dpi = 100)
        a = fig.add_subplot(111)
        a.plot([1,1,1,1,2,3,3,4],[8,9,5,6,2,2,2,2])

        canvas = FigureCanvasTkAgg(fig, master = self.window)
        fig.canvas.draw()
        canvas.get_tk_widget().pack(side = tk.TOP, fill = tk.Y)




start = AppWindow(root)
root.mainloop()

我希望绘制的图形是这样的。 我只举几个例子

enter image description here

稍后我会把它做成

enter image description here


Tags: importself图形plotmatplotlibtkinterdefserial

热门问题