簡體   English   中英

類型錯誤:gassens() 缺少 1 個必需的位置參數:'self'

[英]TypeError: gassens() missing 1 required positional argument: 'self'

此代碼從 esp8266 獲取氣體傳感器(使用“RequestHandler_httpd(BaseHTTPRequestHandler)”)我希望它在收到氣體傳感器時顯示在鍵上(在“class HelloWorld -> def gassens”上)但收到此錯誤:文件“panel2 .py",第 124 行,在 do_GET HelloWorld.gassens() 中類型錯誤:gassens() 缺少 1 個必需的位置參數:'self'

我是 python 的初學者,請幫助 tnx

from tkinter import *
from tkinter.ttk import *
import requests
from http.server import BaseHTTPRequestHandler, HTTPServer
from multiprocessing import Process
import time

gas = 0
hum = ''
g = 0
TheRequest = None
roomp=''
lump = 0
class HelloWorld:
    global lump
    global gas
    def __init__(self, master):
      frame = Frame(master)
      frame.pack()

      frame.columnconfigure(     0, pad    = 2)
      frame.columnconfigure(     1, pad    = 2)
      frame.rowconfigure(        0, pad    = 2)
      frame.rowconfigure(        1, pad    = 2)
      frame.rowconfigure(        2, pad    = 2)


      self.button = Button(
            frame, text="Hello", command=self.button_pressed
            )
      #self.button.pack(side=LEFT, padx=5)
      self.button.grid(row=0, column=0, pady=10, padx=10, sticky=W+E+N+S)

      self.label = Label(frame, text="this is label")
      #self.label.pack()
      self.label.grid(row=0, column=1)

       buttonStyle = Style()
      buttonStyle.configure(  "Normal.TButton",
                            background        = "#91C497",
                            borderwidth       = 1,
                            activeforeground  = "#30903C",
                            compound          = "BOTTOM")
      buttonStyle.configure(  "Selected.TButton",
                            background        = "#107B1D",
                            borderwidth       = 1,
                            activeforeground  = "#30903C",
                            compound          = "BOTTOM")

      self.fanImage = PhotoImage(file="icons/ac.png")
      self.addImage = PhotoImage(file="icons/add.png")
      self.extractor_button = Button(   frame,
                                      text      = "Extractor",
                                      command   = self.toggleFan,
                                      image     = self.fanImage,
                                      style     = "Normal.TButton")
      #self.extractor_button.pack()
      self.extractor_button.grid(row=1, column=1)

      self.label2 = Label(frame, text="gas-sensor is here")
      self.label2.grid(row=2, column=0, columnspan  = 2)


    def button_pressed(self):
      TheRequest = requests.get('http://192.168.43.91/off')


     def toggleFan(self):
      global lump
      if lump == 0 :
        TheRequest = requests.get('http://192.168.43.91/on')
        self.extractor_button.config(image=self.fanImage,style="Selected.TButton")
        lump = 1
      else :
        TheRequest = requests.get('http://192.168.43.91/off')
        self.extractor_button.config(image=self.fanImage,style="Normal.TButton")
        lump = 0

#PROBLEM HERE    
    def gassens(self):
      global gas  
      self.label2.config(text=gas)
    

class RequestHandler_httpd(BaseHTTPRequestHandler):
  def do_GET(self):
    global gas
    global hum
    global g
    print('you got this massage')
    print("request ::",self.requestline)

    req = self.requestline
    tstgas = req.find ("gas")
    tsthum = req.find ("hum")
    if tstgas == 5 :
        gas = str()
        gas = req.replace("GET /gas", "")
        gas = gas.replace(" HTTP/1.1", "")
        print("gaz :"+gas)
        gas = int(gas)
#PROBLEM HERE
        HelloWorld.gassens()
    
    messagetosend = bytes('this is from pi',"utf")
    self.send_response(200)
    self.send_header('Content-Type', 'text/plain')
    self.send_header('Content-Length', len(messagetosend))
    self.end_headers()
    self.wfile.write(messagetosend)
    return
def server_rp():
  global gas
  global g
  try:

      server_address_httpd = ('192.168.43.211',8080)
      httpd = HTTPServer(server_address_httpd, RequestHandler_httpd)
      print('server is started!')
      httpd.serve_forever()
  except:
      print("khata dar server")

def main():
  root = Tk()
  root.geometry("250x150+300+300")
  ex = HelloWorld(root)
  root.mainloop()

if __name__ == '__main__':
  p1 = Process(target=main)
  p1.start()
  p2 = Process(target=server_rp)
  p2.start()
  p1.join()
  p2.join()

這不是您在 Python 中調用方法的方式。 如果是 Java 和 gassens 是 static,你可以這樣做。 但是,Python 中沒有 static 變量的概念。

HelloWorld.gassens()

相反,您想創建 class 的實例以使用 function 氣體傳感器。 例如:

gas = HelloWorld(masterParam)
gas.gassens()

您不能直接在另一個進程中訪問 tkinter 小部件。 因此,在 HTTP 服務器部分使用threading.Thread而不是multiprocessing.Process ,並在主線程中運行 tkinter GUI。

以下是基於您的代碼的建議更改:

from threading import Thread
...
class HelloWorld:
    ...
    def gassens(self, gas):
        self.label2.config(text=gas)

class RequestHandler_httpd(BaseHTTPRequestHandler):
    def do_GET(self):
        # send back response
        messagetosend = b'this is from pi'
        self.send_response(200)
        self.send_header('Content-Type', 'text/plain')
        self.send_header('Content-Length', len(messagetosend))
        self.end_headers()
        self.wfile.write(messagetosend)

        req = self.requestline
        tstgas = req.find('gas')
        if tstgas == 5:
            # requestline: GET /gasXXX HTTP/1.1
            gas = req.split()[1][4:]
            print('gaz:', gas)
            ex.gassens(gas)
...
if __name__ == '__main__':
    # run tkinter GUI in main thread
    root = tk.Tk()
    root.geometry('250x150+300+300')
    ex = HelloWorld(root)
    # using thread instead of process
    Thread(target=server_rp, daemon=True).start()
    root.mainloop()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM