I need help to get this clock to refresh the time - python-3.x

I've been trying to get this program to refresh the time but cannot find away to get it to refresh.
I've tried multiple different ways to make to this script work but cannot find a way to make it refresh.
import datetime
import os
clear = lambda: os.system('cls')
Time = datetime.datetime.now()
def DateTime():
print(Time)
input("\nPress ENTER to refresh: ")
clear()
while True:
DateTime()
I expect the program to refresh the time but it doesn't, and if I knew how to fix this I would of already.

In your code when you define the value of 'Time`, you never update it. The program keeps it binded to the initial value for the rest of it's life span.
It is never updated, what you need to do is get the latest value of time in your function so that the call to DateTime() would give you the latest time.
def DateTime():
print(datetime.datetime.now())
input("\nPress ENTER to refresh: ")
clear()
There are many things you can do in your code to achieve this, this is just one of the ways.

Related

How to run infinite-loop python script that includes external .py script that's non-blocking but yet needs a response

I have two .py scripts. One is a infinite-loop(infinite.py) and the other is a test order on a website(order.py).
I need to execute order.py externally for x. I need this to be non blocking so that my infinite loop can keep checking the other items to see if I need to run order.py for the next "x" that gets popped out from list. The problem is that order.py takes 2 minutes to complete and I need a return of some kind to perform some logic that states if the order was successful, to add x back to list. I do not want "x" to be back in list yet or else it will try to perform another order.py on the same item from list.
I have tried to use subprocess.Popen and call but I can't seem to get them to work. I can either get it to run externally and be non-blocking but I won't be able to get my response from order.py or I get order.py to run but the infinite.py is waiting for order.py to finish before continuing with loop. I have also tried threading as well
Here is the structure of my code.
list = ["item1", "item2", "item3", "item4"]
while True:
x = list.pop(0)
#Performs a simple check 1
if check is True:
#Performs check 2
if check2 is True:
# This is the section I need help with.
# I need to execute order.py and wait for a response while this
# infinite loop keeps going
if order.py is successful:
list.append(x)
else:
print("Problem with order.py")
list.append(x)
else:
list.append(x)
time.sleep(30)
pass
else:
list.append(x)
time.sleep(30)
pass
So after asking a few people I realized what I am trying to do will never work. An example that explained to me was imagine a hand of poker where the current hand is no finished so you do not know the results of your earning before placing a new bet with your current chips. I am closing this post.

Print Current Time In Tkinter

I have written some code in python for a live time in tkinter.
Whenever I run the code it comes up with some numbers on the tkinter window like 14342816time. Is there a way to fix this?
import tkinter
import datetime
window = tkinter.Tk()
def time():
datetime.datetime.now().time()
datetime.time(17, 3,)
print(datetime.datetime.now().time())
tkinter.Label(window, text = time).pack()
window.mainloop()
After some fixes to your code, I came up with the following, which should at least get you started toward what you want:
import datetime
import tkinter
def get_time():
return datetime.datetime.now().time()
root = tkinter.Tk()
tkinter.Label(root, text = get_time()).pack()
root.mainloop()
The imports are needed so that your program knows about the contents of the datetime and tkinter modules - you may be importing them already, however, I can't tell that for certain from what you posted. You need to create a window into which you put your label, which wasn't happening; following convention, I called that parent (and only) window "root". Then I put the Label into root. I changed the name of your time() function to get_time(), since it's best to avoid confusing fellow programmers (and maybe yourself) with a function that shares its name with another (the time() function in time). I removed two lines in get_time() that don't actually accomplish anything. Finally, I changed the print you had to a return, so that the value can be used by the code calling the function.
There are other improvements possible here. If you're content with the time as it is, you could eliminate the get_time function and just use datetime.datetime.now().time() instead of calling get_time(). However, I suspect you might want to do something to clean up that time before it is displayed, so I left it there. You might want to research the datetime and time modules some more, to see how to clean things up.

Timer that runs in the background in Python 3.7.0

I am trying to make a timer in my text-based adventure games so that for every second that passes, 1 hp is taken away from the user, while they are in a certain scenario and can still use other functions. Here's my code:
#Imports and base variables
import time
import threading
import random
hp=100 #Health
p="snow" #Starting point
invtry=[] #Inventory of Character
#Function to drop health
def hlthdrp():
hp-1
t=threading.Timer(1.0,hlthdrp)
t.start()
while p=="snow" or p=="Snow":
if hp==0 and p=="snow" or p=="Snow":
print ("You died of frostbite")
t.cancel()
threading.wait(timeout=5.0)
As of right now, I'm not getting any errors, but instead, a completely blank shell, or terminal. If anyone could help, that'd be great!
You must call threading.Timer recursively else it only calling one time
And you can use lower() function to compare snow or some string
There is your fixed code i hope it will be usefull for you.
def hlthdrp():
global hp
print(hp)# just for testing
hp=hp-1
if hp!=0:
threading.Timer(1, hlthdrp).start()
hlthdrp()
while p.lower()=="snow":
if hp==0 :
print ("You died of frostbite")
elif hp!=0 :
pass

Can a tkinter button return a value from an entry on-click?

I'm doing an extended project as one of my qualifications in my current College and I chose to write a python Strategy/RPG game. As a result, I ended up with the highest level of Python knowledge (Surpassing my Computing Teacher who only ever uses the basics... and used Tkinter only once a few years ago. Every one else who has decided to make a program, are either coding in Lua, Java, C++, HTML/CSS/Java-Script or, those who are coding in python, they are only using the basics learned from our teacher.)
I say "Highest level of Python knowledge" but really it isn't that high... I only know a little beyond the basics.
As a result, a forum post is the best place I can turn to for help.
So in my game I defined this function:
#"Given_String" is the question that one would want to ask. (With the answer being an integer between 1 and "Choice_Range" (inclusive)
def Value_Error(Given_String,Error_Message,Choice_Range):
while True:
try:
Temp=int(input(Given_String))
if Temp<1 or Temp>Choice_Range:
print(Error_Message)
else:
break
except ValueError:
print(Error_Message)
return Temp
I then wanted to add tkinter to my code, because the game would have to be in a separate window, and not in the console. As a result, I had to change this code so that it displays the "Given_Message" and the "Error_Message" in a tkinter window, and uses the value that has been typed into an entry box when defining "Temp".
I wrote this code to make this work: (Or at least most of it)
#This code is stored in a different file for neatness and hence I had to import "sys" to avoid circular imports.
#This code is made to be flexible so that I can later re-use it when necessary.
#This code starts with the function all the way at the bottom. The rest are made to add flexibility and to structure the algorithm.
#This code hasn't been fully run (Because of the Error crashing the Python Shell) so it can contain other Run-time Errors that I'm not aware of yet.
import sys
def Generate_Window(Window_Name,X_Parameter=5,Y_Parameter=50):
Temp=sys.modules['tkinter'].Tk()
Temp.title(Window_Name)
Temp.geometry(str(X_Parameter)+"x"+str(Y_Parameter))
return Temp
def Generate_Button(Master,Text="Submit"):
Temp=sys.modules["tkinter"].Button(Master,text=Text)
return Temp
def Generate_Entry(Master):
Temp=sys.modules["tkinter"].Entry(Master)
return Temp
def Generate_Label(Master,Given_String):
Temp=sys.modules["tkinter"].Label(Master,text=Given_String)
return Temp
def Com_Get_Entry(Given_Window,Given_Entry):
Temp=Given_Entry.get()
Given_Window.destroy()
return Temp
def Com_Confirm(Given_Window):
Given_Window.destroy()
def Generate_Entry_Box(Given_String):
Entry_Window=Generate_Window("Entry",X_Parameter=300)
Entry_Label=Generate_Label(Entry_Window,Given_String)
Entry_Entry=Generate_Entry(Entry_Window)
Entry_Button=Generate_Button(Entry_Window)
Entry_Button.configure(command=lambda:Com_Get_Entry(Entry_Window,Entry_Entry))
Entry_Label.grid(row=0,columnspan=2)
Entry_Entry.grid(row=1,column=0)
Entry_Button.grid(row=1,column=1)
def Generate_Alert_Message(Given_String):
Alert_Window=Generate_Window("Alert",X_Parameter=300)
Alert_Label=Generate_Label(Alert_Window,Given_String)
Alert_Button=Generate_Button(Alert_Window,Text="OK")
Alert_Button.configure(command=lambda:Com_Confirm(Alert_Window))
Alert_Label.grid(row=0,columnspan=2)
Alert_Button.grid(row=1,column=1)
def Get_Interger_Input_In_Range(Given_String,Error_Message,Choice_Range):
while True:
try:
Returned_Value=int(Generate_Entry_Box(Given_String))
if Returned_Value<1 or Returned_Value>Choice_Range:
Generate_Alert_Message(Error_Message)
else:
break
except ValueError:
Generate_Alert_Message(Error_Message)
return Temp
I already included in my code all that I was struggling with and that I could find an answer to.
I.E: On-click, do a certain action with given parameters.
One thing I could not find, is how to return the entered value to the original (Get_Interger_Input_In_Range()) function after the button has been clicked.
What I mean is something like this:
def Function1(GivenParameter1,GivenParameter2):
Temp=Function2(GivenParameter1)
Temp+=GiverParameter2 #random action
return Temp
def Function2(GivenParameter):
Button=Button(Master,command=Function3).grid()
Entry=Entry(Master).grid()
def Function3():
Temp=Entry.get()
return Temp
In Function1 I want Temp to equal the entered value from Function2.
Is there any way to do this without using classes? (I'm not too familiar with classes yet)
Is there any way to do this at all?
I haven't seen anyone give the answer I was looking for...
Because even if they said to use classes... I still didn't know how to return it (Explanation just below)
#The following code was written quickly for purposes of explaining what I mean. It doesn't actually work... (It seems that the button command is being called automatically...)
from tkinter import *
class Return_Value_In_Entry():
def __init__(self):
self.Master=Tk()
self.Entry=Entry(self.Master)
self.Button=Button(self.Master,text="Submit",command=self.Return())
def Return(self):
self.TempVar=self.Entry.get()
return self.TempVar
The way I see it, the Return() function would return the value to the button and not the function/assignment that called the class ... Which is the same problem I'm having with my code.
If you read this all then I really appreciate it. I hope someone can answer my question and tell me (if it's impossible otherwise) how to use classes to solve my "Little" yet large problem.
I fixed your example code (I think). The main problem is that this:
command=self.Return()
does not do what you think it does. It just assigns return value from Return() to command. This is incorrect. It should be
command=self.Return
This assigns function Return to command. Subsequently, when ever button is pressed, self.Return() is executed.
The full example is here:
from tkinter import *
class Return_Value_In_Entry():
def __init__(self):
self.Master=Tk()
self.Entry=Entry(self.Master)
self.Entry.pack()
self.Button=Button(self.Master,text="Submit",command=self.Return)
self.Button.pack()
self.Master.mainloop()
def Return(self):
self.TempVar=self.Entry.get()
print(self.TempVar)
Return_Value_In_Entry()
Now, whenever you press the Button, the value from the Entry widget is saved into self.TempVar and printed out, just to check if its working. Hope this helps.
Gif showing how the example program works:

Refresh PyGTK window every minute?

I have a PyGTK app that is supposed to be a desktop monitor of some data source. I have it almost complete but there is just this one problem of auto-refreshing.
In my program I want it to fetch data from database and refresh the window every minute. Here's what I have for the refresh function (it refresh once per second now for testing):
def refresh(self):
cnxn = pyodbc.connect(r'Driver={SQL Server};Server=IL1WP0550DB;Database=Customer_Analytics;Trusted_Connection=yes;')
cursor = cnxn.cursor()
cursor.execute("SELECT * FROM TestGroup_test_group_result")
data = []
while 1:
row = cursor.fetchone()
if not row:
break
#data.append([row.TestGroupName, row.PWF, row.Expires, row.TestGroupID])
data.append([str(datetime.now()), row.PWF, row.Expires, row.TestGroupID])
cnxn.close()
self.fill_text(data)
threading.Timer(1, self.refresh).start()
Using this function I can update my window, but it only works when I drag my window around. When I put a series of print statements around, it looks like it is only executing the script when the window is moving.
Anyone know how to fix it?
Additional info: I realize that it only processes the refresh when there is a signal.
With GTK you need to make sure your widgets are only updated from the main thread. You can do this by using a timeout function with gtk.timeout_add() or gtk.timeout_add_seconds(). If you use python's threading functions the widgets are not updated from the main thread and so it does not work. For timeouts of greater than one second you should use gtk.timeout_add_seconds() as it avoids unnecessary wake ups where the timing isn't that critical.
Use gtk.timeout_add(1000, self.refresh) instead of threading.Timer(1, self.refresh).start() did the trick :)
Don't know why though
python3:
from gi.repository import GObject
def refresh_data(self):
[do stuff here]
if self.running:
GObject.timeout_add(1000, self.refresh_data)
Set self.running to False to stop.

Resources