Python using self as an argument [closed]

2024/10/5 14:50:50

I have two classes, one which handles the GUI = GUI(), and one that handles the Client connection to my server = Client(). So, my error report would be:

TypeError: change_state() takes exactly 2 arguments (1 given)

when having a self argument within change_state() in GUI(), and calling GUI.change_state('NORMAL') from Client().

But when not having self as an argument within change_state(), I can't call other functions within the GUI class by using self. And changing GUI.change_state() to GUI().change_state would call the __init__ method on GUI everytime. I hope you understood a tiny bit of what I meant Code:

#!/usr/bin/python
import socket
import time
import tkinter
import threading
from tkinter import *root = Tk()
root.geometry("363x200")
root.resizable(0,0)
root.title("Emsg")
b1 = None
b2 = None
class Client:def __init__(self, host='localhost', port=5000):
##        global b1
##        global b2
##        global b3try:self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)self.server_socket.connect((host, port))time.sleep(0.5)GUI.set_info("Connected...")self.boool = Trueself.gotten = ""self.data = ""GUI.change_state('NORMAL') <<<<<<<<< Problemthreading.Timer(1.0, self.listen).start()except socket.error as error:self.boool = FalseGUI.set_info(str(error)[14:])
##        except:
##            self.boool = False
##            GUI.set_info("An unknown error occured")def leave(self):self.boool = Falseself.server_socket.close()GUI.change_state('DISABLED')GUI.set_info("You have left the chat")GUI.set_v("", "")self.data = ""def listen(self):       while self.boool:try:time.sleep(0.1)self.data = self.server_socket.recv(512)if self.data == bytes('quit', 'UTF-8'):self.leave()GUI.set_info("Server has left the chat")GUI.set_v("", "")elif self.data != self.gotten:GUI.set_v("Server:", self.data, True)self.gotten = self.dataexcept socket.error:self.leave()def send(self, message=''):self.server_socket.send(bytes(message, 'UTF-8'))GUI.set_v("Client:", message)GUI.reset_cmsg()class GUI:def __init__(self):self.client = Noneself.setup_buttons()def setup_buttons(self):global b1global b2global b3b1 = Button(root, text="Send", width=8, state=DISABLED, command=self.send)b1.grid(row=0, column=2)b2 = Button(root, text="Leave", width=8, state=DISABLED, command=self.leave)b2.grid(row=0, column=3)b3 = Button(root, text = "Connect", width = 8, command = self.connect)b3.grid(row = 0, column = 4)def connect(self):self.client = Client()self.first = Truedef leave(self):if self.client:self.client.leave()def send(self):if self.client:self.client.send(textEntry.get())def set_v(name, value, encoding=False):if encoding:v.set("%s: %s\n%s" % (name, str(value, 'UTF-8'), v.get()))else:v.set("%s: %s\n%s" % (name, value, v.get()))if name == "":v.set("")def change_state(self, _state):global b1global b2global b3if _state == 'DISABLED':b1.config(state=DISABLED)b2.config(state=DISABLED)b3.config(command=self.connect) <<<<<<<< Problem if changedto GUI().connectb3.config(text="Connect")textEntry.config(state=DISABLED)elif _state == 'NORMAL':b1.config(state=NORMAL)b2.config(state=NORMAL)b3.config(command=self.leave)b3.config(text="Disconnect")textEntry.config(state=NORMAL)def set_info(value):info.set(value)def reset_cmsg():c_msg.set("")v = StringVar()
info = StringVar()
c_msg = StringVar()Label(root, text="Enter: ").grid(row=0, column=0)
textEntry = Entry(root, state=DISABLED, textvariable=c_msg)
textEntry.grid(row=0, column=1)
statusField = Label(root, textvariable=info, wraplength=200)
statusField.grid(row=1, column=0, columnspan=5, sticky="w")
msgField = Message(root, textvariable=v, width=330, fg="blue")
msgField.grid(row=2, column=0, columnspan=5, sticky="w")GUI()root.mainloop()
Answer

Your question is rather vague, but as far as I can tell you are calling the change_state class method on the GUI class. This won't work, you should instantiate a GUI object, and then call the change_state method on that:

gui = GUI()
gui.change_state('NORMAL')
https://en.xdnf.cn/q/120506.html

Related Q&A

how to shuffle questions in python

please anyone help me i have posted my whole work down can anyone tell me how to shuffle theses five questions it please i will be very thankful.print("welcome to the quiz") Validation = Fals…

Selenium python do test every 10 seconds

I am using selenium (python) testing and I need to test my application automatically every 10 seconds.How can I do this?

Type Object has no attribute

I am working on a program, but I am getting the error "Type object Card has no attribute fileName. Ive looked for answers to this, but none that Ive seen is in a similar case to this.class Card: R…

Generate random non repeating samples from an array of numbers

I made a battleships game and I now need to make sure that the computer doesnt attack at the same spot twice.My idea of it is storing each shots co-ordinates in a variable which gets added to whenever …

How to get back fo first element in list after reaching the end? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 5 years ago.Improve…

Collision detection on the y-axis does not work (pygame)

I am trying to get the collision detection in my code to work. I am using vectors and I want the player sprite to collide and stop when it collides with a sprite group called walls. The problem is that…

Search for string within files of a directory

I need help writing a light weight Python (v3.6.4) script to search for a single keyword within a directory of files and folders. Currently, I am using Notepad++ to search the directory of files, altho…

Extract parent and child node from python tree

I am using nltks Tree data structure.Below is the sample nltk.Tree.(S(S(ADVP (RB recently))(NP (NN someone))(VP(VBD mentioned)(NP (DT the) (NN word) (NN malaria))(PP (TO to) (NP (PRP me)))))(, ,)(CC an…

Click button with selenium and python

Im trying to do web scraping with python on and Im having trouble clicking buttons. Ive tried 3 different youtube videos using Xpath, driver.find_element_by_link_text, and driver.find_element. What am …

Combinations of DataFrames from list

I have this:dfs_in_list = [df1, df2, df3, df4, df5]I want to concatenate all combinations of them one after the other (in a loop), like:pd.concat([df1, df2], axis=1) pd.concat([df1, df3], axis=1) p…