emphasized text
**class HomePage(MDScreen):
profile_pics = StringProperty("")
balance = StringProperty("")
def on_enter(self, *args):
self.list_status()
self.list_post()
self.get_all_info()
def list_status(self):
with open("asset/data/store.json") as f_obj:
data = json.load(f_obj)
for name in data:
self.ids.storyline.add_widget(CircularAvatarImage(
avatar=data[name]['avatar'],
name=name
))**
If I understand correctly, you want list_status() to be called only once.
You could add a guard statement around the list_status() call and use a class instance attribute to track state.
def __init__(self):
self.list_status_needed = True
def on_enter(self, *args):
if self.list_status_needed:
self.list_status_needed = False
self.list_status()
self.list_post()
self.get_all_info()
how is possible to pass a function to a thread like a standard variable,
when i pass function on args , i have a non iterable error
there is a summary of my code
from CallbackThread import CallbackThread
import time
import threading
class foo:
def runSomthing(self,callback):
#do things
callthread = threading.Thread(target=self.newthread, args=(callback))
callthread.start()
def newthread(self,calback):
print("runiing")
while True:
#if receve data (udp)
data = 0
#run mycallbacktest
calback(data)
def mycallbacktest(i):
print("hello world", i)
myobj = foo()
myobj.runSomthing(mycallbacktest)
i have see on similar topics things like that
https://gist.github.com/amirasaran/e91c7253c03518b8f7b7955df0e954bb
and i have try this based on this bu i not sure what this is doing, for me is just call a callback when thread if finished
class BaseThread(threading.Thread):
def __init__(self, callback=None, callback_args=None, *args, **kwargs):
target = kwargs.pop('target')
super(BaseThread, self).__init__(target=self.target_with_callback, *args, **kwargs)
self.callback = callback
self.method = target
self.callback_args = callback_args
def target_with_callback(self):
self.method()
if self.callback is not None:
self.callback(*self.callback_args)
but this d'ont solve what i tring to do
as suggested MisterMiyagi, the awnser a missig comma,
It should be args=(callback,) instead of args=(callback)
(this post is to mark this post close)
I'm currently learning how to write object oriented programming in python and I have this code I wrote (well part of it, some of it is part of the class I'm following)
class Toolbox:
def __init__(self, tool):
pass
class Hammer:
def __init__(self, color):
pass
class Screwdriver:
def __init__(self, size):
pass
class Screw:
MAX_TIGHTNESS = 5
def __init__(self):
self.tightness = 0
def loosen(self):
if (self.tightness > 0):
self.tightness -= 1
def tighten(self):
if (self.tightness < self.MAX_TIGHTNESS):
self.tightness += 1
def __str__(self):
return "Screw with tightness {}".format(self.tightness)
class Nail:
def __init__(self):
self.in_wall = False
def nail_in(self):
if (not self.in_wall):
self.in_wall = True
def remove(self):
if (self.in_wall):
self.in_wall = False
def __str__(self):
return "Nail {}in wall.".format("" if self.in_wall else "not ")
hammer = Hammer("blue")
sdriver = Screwdriver("300")
#tbox = Toolbox()
tool1 = Toolbox(hammer)
tool2 = Toolbox(sdriver)
screw1 = Screw()
print(screw1)
screw1.tighten()
print(screw1)
nail1 = Nail()
print(nail1)
nail1.nail_in
print(nail1)
The output of print(screw1) works but print(nail1) gives me the same output (Nail in wall.) twice instead Nail in wall. I guess there's a problem in my logic and I can't seem to figure it out. Can someone help me?
Thanks!
Marc
You need to call nail_in - just as you are already doing with screw1.tighten. So do this (note the brackets here):
nail1.nail_in()
With this fix, your code works:
Screw with tightness 0
Screw with tightness 1
Nail not in wall.
Nail in wall.
By referring to the function but without the brackets, it is a syntactically valid line of code, but it is just an expression for the function object itself, and as you are not doing anything with it (such as assigning it to a variable), it is then simply discarded.
I've recently needed to do some GUI work with Python and stumbled on Tkinter. For the most part, I like it; it's clean and mostly intuitive and brief. There is, however, one little sticking point for me: sometimes it crashes out of nowhere. The program will run normally five times in a row and then the sixth time, halfway through it will freeze and I will get the error
Tcl_AsyncDelete: async handler deleted by the wrong thread
My efforts to find a solution to this problem, both on this website and others, all have to do with multithreading, but I don't use multiple threads. Not explicitly, anyway. I suspect the fact that I have a timer in the GUI is to blame, but I have not been able to figure out why the error pops up, or indeed why it is so infrequent.
What follows is the shortest tkinter program I've written. This happens in all of them, so I suspect the problem will be easiest to see here. Any and all help is appreciated, just don't point me toward another solution without telling me how it applies to my code, because I assure you, I have looked at it, and it either doesn't apply or I didn't understand how it did. I don't mind having missed the answer, but I'm new to tkinter (and to multithreading in general) so I might need it told more explicitly.
This code is for a simulation of a game show I saw online. Most of it can probably be safely ignored, but I'm pasting it all here because I don't know where the error is from.
import re
from tkinter import Tk, Frame, DISABLED, Button, Label, font, NORMAL, ttk
from random import choice
import winsound
class Question:
def __init__(self, t, a, o):
self.text = t.strip().capitalize() + "?"
self.answer = a.strip().title()
self.options = o
self.firstIsRight = self.answer.lower() == self.options[0].lower()
assert self.firstIsRight or self.answer.lower() == self.options[1].lower(), self
def __eq__(self, other):
return self.text == other.text
def __repr__(self):
return "{1} or {2}, {0}".format(self.text, self.options[0], self.options[1])
class Application(Frame):
def __init__(self, master=None):
self.setup()
Frame.__init__(self, master)
self.grid()
self.customFont = font.Font(family="Times New Roman", size=30)
self.createWidgets()
def setup(self):
self.questions = []
with open("twentyone.txt",'r') as file:
for line in file:
groups = re.split("[,\.\?]",line)
answers = re.split(" or ",groups[0])
self.questions.append(Question(groups[1], groups[2], answers))
def createWidgets(self):
self.gamePanel = Frame(self)
self.gamePanel.grid(column=0,row=0)
self.displayPanel = Frame(self)
self.displayPanel.grid(column=0,row=1)
self.buttonPanel = Frame(self)
self.buttonPanel.grid(column=0,row=2)
self.QUIT = Button(self.buttonPanel,text="QUIT",font=self.customFont,command=self.quit)
self.QUIT.grid(row=0,column=2)
self.BEGIN = Button(self.buttonPanel, text="BEGIN",font=self.customFont, command = self.begin)
self.BEGIN.grid(row=0,column=0)
self.STOP = Button(self.buttonPanel, text="STOP",font=self.customFont, command = self.stop)
self.STOP.grid(row=0,column=1)
self.STOP["state"] = DISABLED
self.TITLE = Label(self.gamePanel,text="21 Questions Wrong",font=self.customFont,bg="Black",fg="White")
self.TITLE.grid(columnspan=2)
self.questionText = Label(self.gamePanel,text="Questions go here",font=self.customFont,wraplength=400)
self.questionText.grid(row=1,columnspan=2)
self.leftChoice = Button(self.gamePanel,text="Option 1",font=self.customFont)
self.leftChoice.grid(row=2,column=0)
self.rightChoice = Button(self.gamePanel,text="Option 2",font=self.customFont)
self.rightChoice.grid(row=2,column=1)
self.timerText = Label(self.displayPanel, text="150",font=self.customFont)
self.timerText.grid(row=0)
self.progress = ttk.Progressbar(self.displayPanel, length=100,maximum=22)
self.progress.grid(row=0,column=1,padx=10)
def begin(self):
self.timer(250)
self.asked = []
self.STOP["state"] = NORMAL
self.leftChoice["state"] = NORMAL
self.rightChoice["state"] = NORMAL
self.restart = False
self.askNewQuestion()
def askNewQuestion(self):
if self.restart:
self.currentQuestion = self.asked[int(self.progress["value"])]
else:
self.currentQuestion = choice([i for i in self.questions if i not in self.asked])
self.asked.append(self.currentQuestion)
self.questionDisplay()
def questionDisplay(self):
self.questionText["text"] = self.currentQuestion.text
self.leftChoice["text"] = self.currentQuestion.options[0]
self.rightChoice["text"] = self.currentQuestion.options[1]
if self.currentQuestion.firstIsRight:
self.leftChoice["command"] = self.correct
self.rightChoice["command"] = self.wrong
else:
self.leftChoice["command"] = self.wrong
self.rightChoice["command"] = self.correct
def correct(self):
self.progress.step()
if self.progress["value"] >= 21:
self.gameOver(True, 21)
else:
if self.progress["value"] >= len(self.asked):
self.restart = False
self.askNewQuestion()
def wrong(self):
self.restart = True
self.progress["value"] = 0
winsound.Beep(750,700)
self.askNewQuestion()
def stop(self):
self.after_cancel(self.timerAfter)
self.BEGIN["state"] = NORMAL
self.STOP["state"] = DISABLED
def gameOver(self, success, longest):
self.after_cancel(self.timerAfter)
self.BEGIN["state"] = NORMAL
self.STOP["state"] = DISABLED
self.questionText["text"] = "Congratulations!" if success else "Too Bad!"
self.leftChoice["text"] = "Game"
self.leftChoice["state"] = DISABLED
self.rightChoice["text"] = "Over"
self.rightChoice["state"] = DISABLED
self.showPoints(success, longest)
def showPoints(self, s, l):
if s:
timeTaken = max(0, 100-int(self.timerText["text"]))
print("You scored {0} points".format(1000-10*timeTaken))
else:
print("You scored no points")
def timer(self, time):
self.BEGIN["state"] = DISABLED
self.STOP["state"] = NORMAL
self.runTimer(time)
def runTimer(self, current=None, resume=False):
if current is not None:
self.current = current
self.timerText["text"] = self.current
if self.current == 0:
self.gameOver(False, len(self.asked)-1)
else:
self.current -= 1
self.timerAfter = self.after(1000,self.runTimer)
root = Tk()
app = Application(master=root)
app.master.title("Score Calculator!")
app.anchor("center")
root.mainloop()
root.destroy()
I have the following Python (3.2) code:
from pygame import *
class Application:
def __init__(self):
self.running = True
self.display_surface = None
self.size = self.width, self.height = 640, 480
self.old_ticks = pygame.time.get_ticks
self.new_ticks = None
pygame.init()
self.display_surface = pygame.display.set_mode(self.size, pygame.HWSURFACE | pygame.DOUBLEBUF)
def on_event(self, event):
if event.type == pygame.QUIT:
self.running = False
def on_loop(self):
pass
def on_render(self):
pass
def on_cleanup(self):
pygame.quit()
def regulate_time(self):
self.new_ticks = pygame.time.get_ticks
while (self.new_ticks < self.old_ticks + 1000):
pass
self.old_ticks = self.new_ticks
def load_images(self):
pass
while(self.running == True):
for event in pygame.event.get():
self.on_event(event)
self.regulate_time
self.on_loop()
self.on_render()
self.on_cleanup()
test = Application
I'm having a problem with the following line:
while(self.running == True):
which throws me the error : NameError: Name "self" is not defined.
I am pretty much a python newbie and was hoping to use this time to get started on learning python and pygame which I could then use for my college project (two birds with one stone) and I cannot figure out why this error is being thrown at me.
Well, the while(self.running == True) is not in any method (def) so there is no such variable called self in scope (which is what the NameError says)...
...perhaps there is some missing indentation? Although the previous pass makes it look like more than this is missing: maybe def run(self):?
Remember, self is just the conventional (and proper) name given to the first parameter for a method by which the "current instance" is implicitly passed.
Happy coding.