I've been working on a Python program, in which I simple do not understand why using the function
win32gui.MoveWindow() returns false and prints "fail". It seems like the parameter types are correct, (i.x, i.y, i.w, i.h all are integers). Yet, the function fails to move the Window. I'm assuming that the function returning false most likely means that it failed to move the window to the provided position. Extra note: I'm providing the hwnd of Opera.exe, if somehow that's the cause of this.
if win32gui.MoveWindow(hwnd, int(i.x), int(i.y), int(i.w), int(i.h), True):
print("scs")
else:
print("fail")
I wonder why. I've used a for loop to loop through an array of custom class objects, (which is "i"), and the class is this:
class window(object):
def __init__(self, process):
self.x = 0
self.y = 0
self.w = 0
self.h = 0
self.process = process
And the hwnd I'm providing as the parameter isn't invalid either, as I'm
using win32gui.EnumWindows(fixWindows, None) where "fixWindows" is the function name. I've tried debugging the title of these hwnd's, and they don't seem wrong.
Thanks!
Edit: This function also didn't work as required.
Related
I'm learning about classes in Python, particularly about nested classes.
I'm trying to execute the below code and I get an error: int object is not callable, but
I don't understand why!
All I want is to create an object that identify Man, and he has hands, and the hands have their own size, length, etc...
I want to be able to set the hand size and get its value in the most elegant and easy way as possible and nothing work for me... I tried the below code and I really thought it would work but it didn't and now I know that "I Don't know" what to do for real.
class Man:
def __init__(self, name):
self.name = name
self.hand = self.Hand_Object() # Here we reference an Object called
# "hand" to the subvlass "Hand_Object".
def length(self , length):
self.length = length
def handsize(self, size=None): # This "handsize()" function will call the
# subclass function "length()" out from the
# Hand_Object vlass when it will be issued
# in the program.
if size==None:
return = self.hand.length()
else:
self.hand.length(size) # The "length()" function of the "Hand_Object"
# class requires a variable, so when we call
# that function we need to add a variable to it.
class Hand_Object:
def length(self, length=None):
if length == None:
return self.length
else:
self.length = length
def fingers(self, fingers):
self.fingers = fingers
myman = Man('shlomi')
myman.handsize(6)
print(myman.handsize()) # Here I get the error.
The issue is the line self.length = length in Hand_Object. You're overwriting the function length with an integer. You should call the function and the variable something different.
I am currently trying to create a game object that changes pixmap whenever it moves via .setPos() in a QGraphicsScene. Since I'm new to all this, I'm not sure what the most performance-efficient methods are to cache pixmaps or to change images.
I've already looked at QPixmapCache and re-implementing the paint() function, but I'm still unsure what the best method is. This is the idea I've got at the moment:
class Object(QGraphicsPixmapItem):
def __init__(self):
super(Object, self).__init__()
self.state = 0
self.img = {
"pix1": QPixmap("pix1.png"),
"pix2": QPixmap("pix2.png"),
"pix3": QPixmap("pix3.png")}
def changePix(self):
if self.state == 0:
self.setPixmap(self.img["pix1"])
elif self.state == 1:
self.setPixmap(self.img["pix2"])
elif self.state == 2:
self.setPixmap(self.img["pix3"])
I would appreciate any advice or feedback I can get.
I've never had to use a QPixmapCache object to avoid any performance issue previously, but that's going to depend on what exactly you're doing. If you're just switching between 5 or so relatively small static/generated images (.png < 20kB), I would say it's not necessary. But if you're going to be doing something like a 2k paint buffer with an undo function, or some graph that would need to be regenerated after some paint event, you'll want some sort of caching in place. I refactored your code a bit as well to avoid hard-coding anything.
class Object(QGraphicsPixmapItem):
def __init__(self, *args):
super(Object, self).__init__()
self.img = [a for a in args if os.path.exists(a)]
def load_image(img_path, set_now=False):
if img_path not in self.img:
self.img.append(img_path)
if set_now:
self.change_state(img_path)
def change_state(img_path):
if img_name in self.img:
self.setPixmap(QPixmap(self.img[self.img.index(img_path)]))
I know there are many questions that touch upon this area, but none have clearly answered the problem I'm facing (or perhaps I'm just really thick).
So I'm transferring functional python code to OOP python, and I have some code
class fake_class:
def __init__(self, data_type=None):
if data_type is None:
self.data_type = ""
else:
self.data_type = data_type
def printToLog(x='', *args):
if args:
x = x.format(*args)
else:
x = str(x)
logFile.write(x)
logFile.write('\n')
print(x)
if __name__ == '__main__':
main()
def main(self):
self.printToLog('this is just an example, for some fake code')
f = fake_class('data-xml-435')
# please appreciate that the full code is over 500 lines
# long that has been edited down for the sake of readability
I need the main method to be able to call other methods in the class, but no matter what I do, I cannot manage to allow it to do so. I have made printToLog into a classmethod, I have tried different ways of instantiating the fake_class, calling and all to no avail. The program complains that it doesn't know what printToLog is, what self is or what fake_class is!
So how might I call a method with another method within Python?
if __name__ == '__main__':
main()
does not make any sense with class. You just don't need them.
With that removed, you have to call main explicitly using the object you created.
f = fake_class('data-xml-435')
f.main() # or f.printToLog(with arguments) whichever is exciting you!
Again, printToLog is function of class, so you need a self:
def printToLog(self, x='', *args):
if args:
x = x.format(*args)
else:
x = str(x)
logFile.write(x)
logFile.write('\n')
print(x)
My example is a progress bar
In its simplest form a progress bar is
bar = ProgressBar.Open()
for item in list:
bar.Update(count, len(list))
I would instead like my calling code to be
for item in list:
bar.Update(count, len(list))
I want my Update() function to Open() a bar for the caller if one is not open. The caller doesn't need any other access to the bar than to update it so there's no value in having the meter` handle.
How can I retain state to tell if the Update had been previously called?
I could create a global variable and keep track that way, but I have a gut sense there's a Pythonista way of doing it.
Trying again, but in a way that has no application to stumble on.
The base question is:
I have a function that will be called multiple times.
I want to do something different the first time it is called.
How can a function in Python do that?
In C, that of course would be a...
static variable
I'm just now kinda figuring it out as I type, sorry.
========================
I'm sure all these edits are not how stackoverflow is supposed to work. I'm sorry for not getting it right yet, but am very appreciative of the replies.
Despite it sounding like I'm breaking all the rules of good practices, it's when looked at from the CALLER'S point of view that I had hoped to make an impact.
What if the only thing you needed to do to add a progress meter, even for debugging, to your program was make a call to a progress meter update in the location you want to show progress?
That's the underlying motivation. Slide in 1-line, get something cool for the trouble.
This progress meter was added to my otherwise boring file de-duplicator by adding just the single call:
msg = f'Deduplicating {idx} of {total_files} files\n' f'{dup_count} Dupes found\n' f'{small_count} Too small'
not_cancelled = sGUI.ProgressBar('De-dupe', msg, idx, total_files)
To avoid using global variables, you can use decorator. Here's a simple example:
def open():
print 'open'
def update():
print 'update'
def call_once(func1, *args1, **kwargs1):
def decorator(func2):
called = [False]
def wrapper(*args2 ,**kwargs2):
if not called[0]:
func1(*args1, **kwargs1)
called[0] = True
return func2(*args2, **kwargs2)
return wrapper
return decorator
#call_once(open)
def my_update():
update()
for i in xrange(5):
my_update()
which give the result:
open
update
update
update
update
update
For more information about decorator, please visit: https://wiki.python.org/moin/PythonDecorators
For what you want, you can use a class:
class ProgressBar:
def __init__(self):
self._opened = False
def Open(self):
print("Open")
def Update(self):
if self._opened:
print("Update!")
else:
self.Open()
print("set flag")
self._opened = True
print("Update")
In action:
In [32]: bar = ProgressBar()
In [33]: bar.Update()
Open
set flag
Update
In [34]: bar.Update()
Update!
Note: I copied your casing so as to make it more clear to you, however, the official Python style would be like this:
class ProgressBar:
def __init__(self):
self._opened = False
def open(self):
pass # open stuff
def update(self):
if self._opened:
pass # update stuff
else:
self.open()
self._opened = True
Using snake_case for everything except the ClassName.
OK, I found a solution using 'globals'. I thought that a nested function was the way to do it... then I mixed the two.
By 'globals' I meant variables declared outside the scope of a function. I want to be able to import my module without the import creating anything.
Here's the code that shows how to do this with globals
def my_update(amount):
global flag
if 'flag' in globals():
print('I have been here')
else:
print('I have not been here')
flag = True
return
for i in range(10):
print(f'Calling number {i}')
result = my_update(1)
It does the job for the goals I had set out, but I'm SURE there are better, safer ways that are more elegant as well.
I posted this question on a Python forum and got back the best answer so far using a function attribute. It's brilliant and it works.
Here is code that demonstrates this construct... it should go in everyone's 'Favorite Python Constructs' notebook in my opinion.
def func():
if not hasattr(func, 'static_variable'):
func.static_variable = 0
func.static_variable += 1
return func.static_variable
def main():
for i in range(10):
print('func = {}'.format(func()))
if __name__ == '__main__':
main()
The output is
func = 1
func = 2
func = 3
func = 4
func = 5
func = 6
func = 7
func = 8
func = 9
func = 10
So I am making a text based adventure game. I am working on the engine right now and I am stuck after long hours searching for a solution for this problem.
I have a class called use_action. One of the arguments for that class is a name of a function. I would like to be able to create this action and have a possible custom function incase the item that calls this use_action does something specific.
The custom function I am working with right now is where the player is hurt and is losing 5 HP every so many seconds.
This should start when he uses a specific item and then stops when he uses the medicine that will link to the stop function. The problem I have is that the function gets called immediately. Even though I am trying to call it at the end of a long if else statement. And then when i get to where i am trying to call it it doesn't call.
I am not posting the whole class as it along with its functions are about 150 lines of code.
class use_action(object):
def __init__(self, function = None):
self.function = function
pizza_act = use_action(function = mechanics.tmr.start())
#This is located at the end of an if else statement after the player types use . . .
if self.function != None:
self.function
else:
pass
From Mechanics:
thread_list = []
class TimerClass(threading.Thread):
def __init__(self, function, time):
threading.Thread.__init__(self)
self.event = threading.Event()
self.function = function
self.time = time
thread_list.append(self)
def run(self):
while not self.event.is_set():
self.event.wait( self.time )
self.function()
def stop(self):
self.event.set()
def blank_current_readline():
# Next line said to be reasonably portable for various Unixes
(rows,cols) = struct.unpack('hh', fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ,'1234'))
text_len = len(readline.get_line_buffer())+2
# ANSI escape sequences (All VT100 except ESC[0G)
sys.stdout.write('\x1b[2K') # Clear current line
sys.stdout.write('\x1b[1A\x1b[2K'*(text_len/cols)) # Move cursor up and clear line
sys.stdout.write('\x1b[0G') # Move to start of line
def pizza_poisoned_action():
# threading.Timer(10, pizza_poisoned_action).start()
blank_current_readline()
print "You lost 5 hp."
initialization.gamer.hp -= 5
sys.stdout.write('> ' + readline.get_line_buffer())
sys.stdout.flush() # Needed or text doesn't show until a key is pressed
tmr = TimerClass(pizza_poisoned_action, 5)
Sorry about the length, I tried to only post the relevant stuff for this. If you think i should post some other piece of code that may be relevant let me know!
If you want to pass a function, don't call it. Or else, you'll be passing the return value.
pizza_act = use_action(function = mechanics.test()) #Wrong!
pizza_act = use_action(function = mechanics.test) #Right