Python Plot showing live SQL data on Tkinter Canvas

I have written a piece of code where I have a simple GUI with an Tkinter Canvas. On this canvas I draw an Matplot. The Matplot is updated every second with fake sensor data i simulate in an SQLite DB (just for testing at the moment).

I reached most of my Goals for this test case. But a few Things i would like to have reviewed:

  1. The Performance seems to be not really good. The window is lagging if you drag it over the Desktop. I think this is caused by the redrawing of the Canvas. I tried to use threads but failed to not Interrupt my mainloop while updating the canvas.
  2. My Code seems pretty messy (I am a beginner and just learning how to Code in a good style). Every criticism and ideas to make it better are welcome.

So here is my Code so far:

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure import tkinter as tk import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import sqlite3 from datetime import datetime from random import randint  class MainApplication(tk.Frame):     def __init__(self, parent, *args, **kwargs):         tk.Frame.__init__(self, parent, *args, **kwargs)         self.parent = parent          root.update_idletasks()          f = Figure(figsize=(15,5), dpi=55)                 x=1         ax = f.add_subplot(111)         line, = ax.plot(x, np.sin(x))               def animate(i):             # Open Database             conn = sqlite3.connect('Sensor_Data.db')             c = conn.cursor()             # Create some fake Sensor Data                 NowIs = datetime.now()             Temperature = randint(0, 100)             Humidity = randint(0, 100)             # Add Data to the Database             c = conn.cursor()             # Insert a row of data             c.execute("insert into Sensor_Stream_1 (Date, Temperature, Humidity) values (?, ?, ?)",                         (NowIs, Temperature, Humidity))             # Save (commit) the changes             conn.commit()             # Select Data from the Database             c.execute("SELECT Temperature FROM Sensor_Stream_1 LIMIT 30 OFFSET (SELECT COUNT(*) FROM Sensor_Stream_1)-30")              # Gives a list of all temperature values              x = 1             Temperatures = []              for record in c.fetchall():                     Temperatures.append(str(x)+','+str(record[0]))                 x+=1             # Setting up the Plot with X and Y Values             xList = []             yList = []              for eachLine in Temperatures:                 if len(eachLine) > 1:                     x, y = eachLine.split(',')                     xList.append(int(x))                     yList.append(int(y))                         ax.clear()              ax.plot(xList, yList)               ax.set_ylim(0,100)             ax.set_xlim(1,30)              ax.tick_params(axis='both', which='major', labelsize=12)              ax.grid(b=None, which='major', axis='both', **kwargs)           label = tk.Label(root,text="Temperature / Humidity").pack(side="top", fill="both", expand=True)          canvas = FigureCanvasTkAgg(f, master=root)         canvas.get_tk_widget().pack(side="left", fill="both", expand=True)          root.ani = animation.FuncAnimation(f, animate, interval=1000)  if __name__ == "__main__":     root = tk.Tk()     MainApplication(root).pack(side="top", fill="both", expand=True)     root.mainloop() 

ImageMagick error: zsh: no matches found: canvas: hex color in mac

When creating a png image file which is just a solid rectangle in Mac, I have seen imagemagick: create a .png file which is just a solid rectangle

I use convert -size 100x100 canvas:#ff9900 whatever.png

issue is:

zsh: no matches found: canvas:#ff9900

I use

convert -size 100x100 canvas:`#ff9900` whatever.png 

, reading from http://www.imagemagick.org/script/color.php

Just a white image , not the color I set.

How to get through?

Keysym, keycode и char в Python Canvas

Как переделать код так, чтобы проргамма выводила не только keysym, но и char, keysym_num и keycode.

import tkinter   def show_key(event):     label.config(text=event.keysym)   master = tkinter.Tk() label = tkinter.Label(master, text="Hello world!") label.pack() master.bind("<KeyPress>", show_key) master.mainloop() 

Flutter: Конфликт скролла между listView и Canvas

Всем привет! В общем я имею listView, в нем один из элементов gestureDetector, в котором находится canvas. Канвас отрисовывает схему.

Мне нужно чтобы это схема увеличивалась и “скролилась”. Саму логику я уже прописал и все работает, но! Если начать движение в области канваса вверх или вниз, то будет двигаться не канвас, а скролиться listView. Я загуглил интернет до дыр, но ничего не нашел. Грубо говоря мне нужно чтобы когда пользователь двигал вверх/вниз в области gestureDetector, все события посылались туда, а в listView(родительский комнонент) не посылались.

ListView ( ...     child: GestureDetector(     ...        child: ...              child: CustomPaint(...)) ) 

Substituir/alternar slider1.value() por slider2.value() dentro de uma variável no código e dentro da posição no canvas

Gostaria de substituir/alternar o slider que dá valor a uma variável dentro de um objeto. O slider2 deve subsituir e ocupar dentro do código e também no canvas o lugar que antes ocupava o slider1, e vice-versa. Vamos supor:

var slider1; var slider2;  function setup() { createCanvas (windowWidth, windowHeight);  slider1 = createSlider(0, 255, 125); slider1.position(100, 100);  slider2 = createSlider(0, 500, 125); slider2.position(100, 100); }  function draw(){ background(0);   translate(width/2, height/2);  stroke(255); strokeWeight(5); noFill(); ellipse(50, 50, slider1.value(), slider1.value()); } 

Eu gostaria de, ao acionar algo como uma função keyPressed ou algo assim, substituir o “slider1.value()” pelo “slider2.value()”, ali na ellipse.

Um outro problema é posicionar o slider dentro do canvas.

Ao mesmo tempo que gostaria de substituir slider.value(), preciso substituir também o “slider1.position” pelo “slider2.position”, já que um vai ocupar o lugar do outro no canvas.

Tentei fazer algo como criar uma função keyPressed depois do function draw, da seguinte forma:

var slider1; var slider2; var value;  function setup() { createCanvas (windowWidth, windowHeight);  slider1 = createSlider(0, 500, 100); slider2 = createSlider(0, 300, 100);  }  function draw() {  background(150); translate(width/2, height/2);  value = slider1.value(); stroke(255); noFill(); strokeWeight(2); ellipse(0, 0, value, value);  }     function keyPressed(){  if (keyCode == DOWN_ARROW) { value = slider2.value(); slider2.position(100, 100);  } else {  value = slider1.value(); slider1.position(100, 100); } } 

mas não deu muito certo, porque se o slider não for criado já no setup, inicialmente aparece situado fora do canvas, o que não me interessa, porque na real a composição é mais complexa, com vários elementos e botões.

E um outro problema derivado disso é que por final, os dois sliders ficam sobrepostos. Eu gostaria que um sumisse para que o outro aparecesse e vice-versa.

Uma solução provisória para não sobrepor os sliders foi, dentro da condição, jogar um ou outro para fora da tela:

var slider1; var slider2;   var value = 50;  function setup() { createCanvas (windowWidth, windowHeight);  slider1 = createSlider(0, 500, 100); slider1.position(100, 100);  slider2 = createSlider(0, 50, 50); slider2.position(-300, 100);  }  function draw() { background(150); translate(width/2, height/2);  stroke(255); noFill(); strokeWeight(2); ellipse(0, 0, value, value); }  function keyPressed(){  if (keyCode == 'DOWN_ARROW') {  value = slider2.value(); slider2.position(100, 100); slider1.position(-300, 100);  } else {  value = slider1.value(); slider2.position(-300, 100); slider1.position(100, 100); } } 

De toda forma, não está respondendo como o esperado.

Espero ter sido claro o suficiente. Agradeço a atenção. Abs e feliz ano-novo!

How to get a canvas element above the footer?

I’m struggling to get the canvas to be above the footer while using a three.js script. I pass my canvas in to webglrenderer, but then it pops the canvas to the bottom and puts the footer above it.

Any ideas how to get the canvas inside the content and not under the footer?

  <?php     get_header();      ?>     <h1>My Title</h1>      <canvas id="myCanvas" style="width:400px; height:400px;"></canvas>       <script>         var canvas1 = document.getElementById("myCanvas");          var scene = new THREE.Scene();         var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );         var renderer = new THREE.WebGLRenderer({ canvas: canvas1 });         renderer.setSize( window.innerWidth, window.innerHeight);         document.body.appendChild( renderer.domElement );          //create the shape         var geometry = new THREE.BoxGeometry( 1, 1, 1);          //create a material, color, or image         var material = new THREE.MeshBasicMaterial( {color:0xFFFFFF,wireframe:true});         var cube = new THREE.Mesh( geometry, material );         scene.add( cube );          camera.position.z = 3;          //game logic         var update = function()         {             cube.rotation.x += 0.01;             cube.rotation.y += 0.005;          };          //draw scene         var render = function()         {             renderer.render(scene, camera);         };          //run game loop         var GameLoop = function(){             requestAnimationFrame( GameLoop );              update();             render();         };          GameLoop();      </script>       <?php     get_footer();     ?> 

How to center canvas in GIMP

When I create a new document in GIMP the default canvas is not centered and is aligned to top. this creates problems because if by a slight mistake I go above the canvas, the menus are clicked accidentally. This is awkward. I want to center the canvasenter image description here

I have tried in preferences but no relevant option was there.

I tried view>>Navigation, clicking one of the bottom buttons enlarges it but there is no option to center the canvas. How can I center the canvas for example in this video. https://www.youtube.com/watch?v=TzYdQE1Tbyw (Please ignore the contents of the video and its title. I am talking about the way canvas is displayed in his GIMP window).

View post on imgur.com

cancelAnimationFrame no limpia mi canvas

Dentro de este canvas

<canvas id="canvas" class="canvas" width="300" height="300"></canvas> 

Tenga esta función

var estado = false; var canvas = document.getElementById('canvas'); var ctx = canvas.getContext("2d"); function frame(){   actualizar();   coliciones();   dibujar();   bucle = requestAnimationFrame(frame);  }  function startStop(){   if (!estado) {     estado = true;     frame();       console.log('game init :'+estado);   }else {     estado = false;     cancelAnimationFrame(bucle);     console.log('game estatus :'+estado);   } 

pero cancelAnimationFrame no borra o no hace un clear a mi canvas. Pero si estoy recibiendo los log’s de mi consola, alguien podrìa decime si hago algo mal?