Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 未使用textvariable更新Tkinter标签_Python_Tkinter_Label_Figure - Fatal编程技术网

Python 未使用textvariable更新Tkinter标签

Python 未使用textvariable更新Tkinter标签,python,tkinter,label,figure,Python,Tkinter,Label,Figure,在我的代码中,我看到标签没有被“textvariable”更新,尽管我相信我做得对(可能不是!) 这应该显示一个写有“默认值”的标签。问题是我没有看到任何书面材料。 我把代码贴在这里了 import matplotlib import matplotlib.artist as artists import matplotlib.pyplot as plt #import matplotlib.mlab as mlab import scipy.stats from matplotlib.bac

在我的代码中,我看到标签没有被“textvariable”更新,尽管我相信我做得对(可能不是!)

这应该显示一个写有“默认值”的标签。问题是我没有看到任何书面材料。 我把代码贴在这里了

import matplotlib
import matplotlib.artist as artists
import matplotlib.pyplot as plt
#import matplotlib.mlab as mlab
import scipy.stats

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, 
NavigationToolbar2Tk
from matplotlib.figure import Figure
import matplotlib.animation as animation
from matplotlib import style

import numpy as np
import statistics

from tkinter import *
from tkinter import ttk

import serial
import time

import itertools

integer=0
xList = []
humidityList = []
humidityListHistogram = []
temperatureList = []
temperatureListHistogram = []
cnt=0

if sys.platform.startswith('win'):
        ports = ['COM%s' % (i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
    # this excludes your current terminal "/dev/tty"
    ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
    ports = glob.glob('/dev/tty.*')
else:
    raise EnvironmentError('Unsupported platform')

ser = serial.Serial()

style.use("seaborn-whitegrid")

#varmuTemperature = StringVar()
#varmuHumidity = StringVar()

f=plt.figure(0, figsize=(20,10))

humidityGraph = plt.subplot(224)
humidityGraph.set_title("Humidity vs Time")
humidityGraph.set_ylabel("Humidity RAW (Dec)")
humidityGraph.set_xlabel("Sample ()")


temperatureGraph = plt.subplot(223)
temperatureGraph.set_title("Temperature vs Time")
temperatureGraph.set_ylabel("Temperature RAW (Dec)")
temperatureGraph.set_xlabel("Sample ()")

humidityGraphHistogram = plt.subplot(222)
temperatureGraphHistogram = plt.subplot(221)
temperatureGraphHistogramNormal = temperatureGraphHistogram.twinx()
humidityGraphHistogramNormal = humidityGraphHistogram.twinx()

side_text = plt.figtext(0.93, 0.5, 'Text 1'+'\n'+'Text 2', bbox=dict(facecolor='white'))

plt.subplots_adjust(left = 0.05, right = 0.95, bottom = 0.05, top = 0.95, wspace = 0.16, hspace = 0.21)



class make_window():

    def __init__(self, *args, **kwargs):

        win = Tk()

        win.title("Test")
        win.state("zoomed")

        Frame1 = Frame(win)
        Frame1.pack()

        self.comboBoxAvailableCOMPort = ttk.Combobox(Frame1, width = 30)
        self.comboBoxAvailableCOMPort['values'] = []
        self.comboBoxAvailableCOMPort.pack(padx=5, pady=5, side = LEFT)

        self.buttonCheckComAvailable = Button(Frame1, text="Check COM Available", command = self.CheckComAvailable)
        self.buttonCheckComAvailable.pack(padx=5, pady=10, side = LEFT)

        self.buttonOpenCOMPort = Button(Frame1, text="Open COM Port", command = self.OnOpenCom)
        self.buttonOpenCOMPort.pack(padx=5, pady=10, side = LEFT)

        self.buttonCloseCOMPort = Button(Frame1, text="Close COM Port" , command = self.OnCloseCOM)
        self.buttonCloseCOMPort.pack(padx=5, pady=10,side = LEFT)

        self.CheckComAvailable()

        Frame2 = Frame(win, highlightbackground = "red", highlightcolor = "red", highlightthickness = 1)
        Frame2.pack()

        varmuTemperature = StringVar(value="default value")
        varmuTemperature.set("trerta")
        print(varmuTemperature.get())
        self.Label = Label(Frame2, textvariable = varmuTemperature)
        self.Label.pack()

        self.buttonCloseProgram = Button(Frame2, text="Close Program", command = self.OnCloseProgram)
        self.buttonCloseProgram.pack(expand=True, fill='x', anchor='s')


        Frame3 = Frame(win)
        Frame3.pack()

        canvas = FigureCanvasTkAgg(f, Frame3)
        canvas.get_tk_widget().pack(padx=5, pady=10, side=BOTTOM, expand = True)

        toolbar = NavigationToolbar2Tk(canvas, Frame3)
        toolbar.update()
        canvas._tkcanvas.pack(padx=5, pady=10,side = TOP)


    def CheckComAvailable(self):
        self.comboBoxAvailableCOMPort['values'] =[]
        result = []
        for port in ports:
            try:
                s = serial.Serial(port)
                s.close()
                result.append(port)
            except (OSError, serial.SerialException):
                pass
        self.comboBoxAvailableCOMPort['values'] += tuple(result)
        self.comboBoxAvailableCOMPort.set(result[0])

    def OnOpenCom(self):
        ser.baudrate = 115200
        ser.port = self.comboBoxAvailableCOMPort.get()
        try:
            ser.open()
            ser.readline()
            ser.write("#dut,0$\n".encode('utf-8'))
            ser.readline()
            ser.write("#v,1800,1800$\n".encode('utf-8'))
            ser.write("#W,77,08,07$\n".encode('utf-8'))
            ser.readline()

        except(OSError):
            print("COM Port in use")

    def OnCloseCOM(self):
        global xList
        global humidityList
        global temperatureList
        global humidityListHistogram
        global temperatureListHistogram
        global integer
        integer=0
        xList = []
        humidityList = []
        temperatureList = []
        ser.close()

    def OnCloseProgram(self):
        self.OnCloseCOM()
        exit()        

##    def toggle_geom(self,event):
##        geom=self.master.winfo_geometry()
##        print(geom,self._geom)
##        self.master.geometry(self._geom)
##        self._geom=geom


def animate(i):
    global integer
    global cnt
    try:
        ser.write(("#R,77,00,03$" + chr(10)).encode('utf-8'))
        humidityLine=ser.readline()
        inthumidityLine= int(humidityLine,16)
        if (inthumidityLine > 8388608):
            inthumidityLine = inthumidityLine - 16777216
        humidityList.append(inthumidityLine)
        humidityListHistogram.append(inthumidityLine)


        ser.write(("#R,77,03,03$" + chr(10)).encode('utf-8'))
        temperatureLine=ser.readline()
        LineHistogram = temperatureLine
        inttemperatureLine= int(temperatureLine,16)
        if (inttemperatureLine > 8388608):
            inttemperatureLine = inttemperatureLine - 16777216
        temperatureList.append(inttemperatureLine)
        temperatureListHistogram.append(inttemperatureLine)

        xList.append(integer)
        integer+=1

##################################################################################################################
##      Creates the HUMIDITY Graphics
##################################################################################################################

        humidityGraph.clear()
        humidityGraph.plot(xList,humidityList,'-b*', label = "Humidity RAW")
        humidityGraph.legend(loc='upper right', fancybox = True, frameon = True, shadow = True)
        humidityGraph.set_title("Humidity vs Time")
        humidityGraph.set_ylabel("Humidity RAW (Dec)")
        humidityGraph.set_xlabel("Sample ()")

        muHumidity = statistics.mean(humidityListHistogram)
        #print("Mean = " + str(muHumidity) + " ; N = " + str(len(humidityListHistogram)))
        #global varmuHumidity
        #varmuHumidity.set("Humidity: ")
        if (len(humidityListHistogram) > 1):
            sigmaHumidity = statistics.pstdev(humidityListHistogram)
        else:
            sigmaHumidity = 100
        humidityGraphHistogram.clear()
        nHumidity, binsHumidity, patchesHumidity = humidityGraphHistogram.hist(humidityListHistogram, 100, density=False, facecolor='blue', alpha=0.75, histtype = 'stepfilled')

        normalDistHumidity = scipy.stats.norm.pdf(binsHumidity, muHumidity, sigmaHumidity)
        humidityGraphHistogramNormal.clear()
        humidityGraphHistogramNormal.plot(binsHumidity, normalDistHumidity, 'r--')
        humidityGraphHistogram.set_title("Histogram for Humidity Data")
        humidityGraphHistogram.set_ylabel("Humidity RAW Counts (Dec)")
        humidityGraphHistogram.set_xlabel("BINS ()")
        humidityGraphHistogramNormal.set_ylabel("Normal Distribution")

##################################################################################################################
##      Creates the TEMPERATURE Graphics
##################################################################################################################

        temperatureGraph.clear()
        temperatureGraph.plot(xList,temperatureList,'-r*', label = "Temperature RAW")
        temperatureGraph.legend(loc='upper right', fancybox = True, frameon = True, shadow = True)
        temperatureGraph.set_title("Temperature vs Time")
        temperatureGraph.set_ylabel("Temperature RAW (Dec)")
        temperatureGraph.set_xlabel("Sample ()")



        muTemperature = statistics.mean(temperatureListHistogram)
        #global varmuTemperature
        #varmuTemperature.set("Temperature: " )
        if (len(temperatureList) > 1):
            sigmaTemperature = statistics.pstdev(temperatureListHistogram)
        else:
            sigmaTemperature = 100
        temperatureGraphHistogram.clear()
        nTemperature, binsTemperature, patchesTemperature = temperatureGraphHistogram.hist(temperatureListHistogram, 100, density=False, facecolor='red', alpha=0.75, histtype = 'stepfilled')

        normalDistTemperature = scipy.stats.norm.pdf(binsTemperature, muTemperature, sigmaTemperature)
        temperatureGraphHistogramNormal.clear()
        temperatureGraphHistogramNormal.plot(binsTemperature, normalDistTemperature, 'b--')
        temperatureGraphHistogram.set_title("Histogram for Temperature Data")
        temperatureGraphHistogram.set_ylabel("Temperature RAW Counts (Dec)")
        temperatureGraphHistogram.set_xlabel("BINS ()")
        temperatureGraphHistogramNormal.set_ylabel("Normal Distribution")


        if (cnt > 100):
            xList.pop(0)
            humidityList.pop(0)
            temperatureList.pop(0)
        cnt+=1
    except(OSError):
        bla=0



win = make_window()
ani = animation.FuncAnimation(f, animate, interval = 300)
make_window.mainloop()
调试一点并开始注释代码行,我发现问题可能来自

f=plt.figure(0, figsize=(20,10))
注释这一行(以及这一行的所有依赖项)会使标签被写入。 有人能帮忙吗?我不明白为什么图形会干扰标签。
非常感谢。

通常的问题似乎是您对实例变量和对象的管理。作为
self.*
变量,您将永远不需要再次引用的东西,如
buttonCheckComAvailable
,但无法为以后需要引用的东西(如
varmuTemperature
)设置
self.*
变量

就对象而言,你做的事情毫无意义:

make_window.mainloop()
因为
make_window
是一个对象类,而不是一个实例,并且类
make_window
的实例无论如何不会响应
mainloop
,因为它包含一个窗口,但本身不是一个窗口

下面是我的MCVE,它为您的示例代码提供了
varmuTemperature
一个实例变量,并在单击界面上的各种按钮时设置它,以便您可以看到它的工作情况:

from tkinter import *
from tkinter import ttk

class make_window():

    def __init__(self):

        self.win = Tk()

        self.win.title("Test")
        self.win.state("zoomed")

        Frame1 = Frame(self.win)

        self.comboBoxAvailableCOMPort = ttk.Combobox(Frame1, width=30)
        self.comboBoxAvailableCOMPort['values'] = []
        self.comboBoxAvailableCOMPort.pack(padx=5, pady=5, side=LEFT)

        Button(Frame1, text="Check COM Available", command=self.CheckComAvailable).pack(padx=5, pady=10, side=LEFT)

        Button(Frame1, text="Open COM Port", command=self.OnOpenCom).pack(padx=5, pady=10, side=LEFT)

        Button(Frame1, text="Close COM Port", command=self.OnCloseCom).pack(padx=5, pady=10, side=LEFT)

        Frame1.pack()

        Frame2 = Frame(self.win, highlightbackground="red", highlightcolor="red", highlightthickness=1)

        self.varmuTemperature = StringVar(value="default value")
        Label(Frame2, textvariable=self.varmuTemperature).pack()

        Button(Frame2, text="Close Program", command=self.OnCloseProgram).pack(expand=True, fill='x', anchor='s')

        Frame2.pack()

    def CheckComAvailable(self):
        self.varmuTemperature.set("CheckCom")

    def OnOpenCom(self):
        self.varmuTemperature.set("OpenCom")

    def OnCloseCom(self):
        self.varmuTemperature.set("CloseCom")

    def OnCloseProgram(self):
        self.OnCloseCom()
        exit()

window = make_window()

window.win.mainloop()

你发布的代码太多了。请尽量减少到a。当问关于特定问题的问题时,请将代码减少到涉及的部分。我们所需要的只是你的标签textvar和任何应该更新该var的东西。非常感谢你花时间在@cdlane解决我的问题。如果我将代码简化为按钮和框架,我可以看到正在编写的标签,但是如果我包含图形(变量“f”的依赖项),那么它就不再显示了(这就是我将整个代码放在这里的原因)。
from tkinter import *
from tkinter import ttk

class make_window():

    def __init__(self):

        self.win = Tk()

        self.win.title("Test")
        self.win.state("zoomed")

        Frame1 = Frame(self.win)

        self.comboBoxAvailableCOMPort = ttk.Combobox(Frame1, width=30)
        self.comboBoxAvailableCOMPort['values'] = []
        self.comboBoxAvailableCOMPort.pack(padx=5, pady=5, side=LEFT)

        Button(Frame1, text="Check COM Available", command=self.CheckComAvailable).pack(padx=5, pady=10, side=LEFT)

        Button(Frame1, text="Open COM Port", command=self.OnOpenCom).pack(padx=5, pady=10, side=LEFT)

        Button(Frame1, text="Close COM Port", command=self.OnCloseCom).pack(padx=5, pady=10, side=LEFT)

        Frame1.pack()

        Frame2 = Frame(self.win, highlightbackground="red", highlightcolor="red", highlightthickness=1)

        self.varmuTemperature = StringVar(value="default value")
        Label(Frame2, textvariable=self.varmuTemperature).pack()

        Button(Frame2, text="Close Program", command=self.OnCloseProgram).pack(expand=True, fill='x', anchor='s')

        Frame2.pack()

    def CheckComAvailable(self):
        self.varmuTemperature.set("CheckCom")

    def OnOpenCom(self):
        self.varmuTemperature.set("OpenCom")

    def OnCloseCom(self):
        self.varmuTemperature.set("CloseCom")

    def OnCloseProgram(self):
        self.OnCloseCom()
        exit()

window = make_window()

window.win.mainloop()