Skip to content Skip to sidebar Skip to footer

Tkinter Textvariable Not Updated With MatplotLib

Can anyone help me here? The textvariable is not being updated when I add the line: f = plt.figure(0, figsize=(20,9)) If I comment the line above, then I see the textvariable bein

Solution 1:

I have noticed a few issues that you need to address.

First the way you are importing (from tkinter import *) is going to cause problems and in fact here in this case you make the kind of mistake this import is known for. Later in your code you do Frame = ttk.Frame() and this one line is actually overriding the Frame import from from tkinter import *. Do not name your variables the same as built in methods. In order to prevent this kind of mistake you can simply do import tkinter as tk and always use the tk. prefix to prevent any overriding in your code.

Next I noticed your Label does pack to the screen but does not show any text oddly enough but when I comment out f = plt.figure(0, figsize=(20,9)) the Label starts to work as expected.

So there is some odd interaction here with matplotlib and this label.

When I change f = plt.figure(0, figsize=(20,9)) to f = Figure(figsize=(20,9)) the label also works again.

If Figure() is not exactly what you are trying to use here then please add some more context to your code as to what you are expecting to do with f.

Update:

I did also notice that when you move f to be after self.win = tk.Tk() the code works fine. My only guess as to why this is happening is possible how matplotlib does have its own tkinter code in it. So if you try to create a plt.figure before you create your tkinter instance then I imaging in the back end a tkinter instance is being ran by matplotlib and this is what is causing the odd behavior. I could be wrong but I cannot think of anything else. Maybe the Tkinter master Bryan Oakley can enlighten us as to what is causing this :D

import tkinter as tk
import tkinter.ttk as ttk

import matplotlib
import matplotlib.artist as artists
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import matplotlib.animation as animation


class make_window():
    def __init__(self, *args, **kwargs):
        self.win = tk.Tk()
        # moving the line to here should at least allow your code to work.
        f = plt.figure(0, figsize=(20,9))
        self.win.title("Test")
        self.win.state("zoomed")

        frame = ttk.Frame(self.win)
        frame.pack()

        labelVar = tk.StringVar()
        labelVar.set("Hi")
        self.LabelUpdate = tk.Label(frame, textvariable = labelVar)
        self.LabelUpdate.pack()


window = make_window()
window.win.mainloop()

Post a Comment for "Tkinter Textvariable Not Updated With MatplotLib"