I write chess on Python3, use Tkinter. I have a problem with bot-mode. Player correctly play: click on buttons and figures move. After player's turn bot should play.
def main():
start_position()
root.mainloop()
while king_alive:
global bot_turn
if bot_turn:
cells = l.bot_move(log_field)
replace(cells[0], cells[1])
bot_turn = False
this is function replace() which change condition of cells on the field
def replace(first_cell, second_cell):
if second_cell.figure.type != 'nofig':
delete_fig(second_cell.figure)
first_cell.clicked = False
second_cell.clicked = False
second_cell.fig_name = first_cell.fig_name
second_cell.fig_owner = first_cell.fig_owner
second_cell.figure = second_cell.get_figure()
first_cell.figure = l.NoFigure(first_cell.x, first_cell.y, "")
first_cell.fig_name = ""
first_cell.fig_owner = ""
field[second_cell.x][second_cell.y].configure(fg=second_cell.fig_owner, text=second_cell.fig_name)
field[first_cell.x][first_cell.y].configure(text="")
demark_cells()
people can easily play and move figures, but bot can't do it, however he use the same functions of movement - replace() (input for method replace() are correct. I can't understand the traceback
Traceback (most recent call last):
File "C:/Users/Даша/Desktop/python/task chess/graphics.py", line 176, in <module>
main()
File "C:/Users/Даша/Desktop/python/task chess/graphics.py", line 171, in main
replace(cells[0], cells[1])
File "C:/Users/Даша/Desktop/python/task chess/graphics.py", line 138, in replace
field[second_cell.x][second_cell.y]['fg'] = second_cell.fig_owner
File "C:\Python34\lib\tkinter\__init__.py", line 1275, in __setitem__
self.configure({key: value})
File "C:\Python34\lib\tkinter\__init__.py", line 1268, in configure
return self._configure('configure', cnf, kw)
File "C:\Python34\lib\tkinter\__init__.py", line 1259, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: invalid command name ".36689776"
how to solve the problem?
P.S. log_field is matrix of every cell conditions
field is matrix of tkinter buttons
You have a problem in the line:
field[second_cell.x][second_cell.y]['fg'] = second_cell.fig_owner
Because you have destroyed, or assigned a different variable to a widget that is called in that line. I don't know exactly what your variables are, but it is probably field[second_cell.x][second_cell.y]['fg'] or second_cell.
Related
My code keeps giving this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "d:/Python Code stuff I did/print.py", line 209, in <lambda>
button = Button(root,text="Change Config", width=20, height=3, bg="#0f0f0f",fg="#ffffff", command=lambda:[do_it(), do_it1(), do_it2(), do_it3(),do_the_it(),do_the_it1()])
File "d:/Python Code stuff I did/print.py", line 149, in do_the_it
if str(number_1) > 4:
TypeError: '>' not supported between instances of 'str' and 'int'
I want it to check if that specific number is greater than 4 for example i input a number for example lets say its 7 I want it to print and that number is too high here is my code:
def do_the_it():
a = updater['Trading Settings']['minimum_offer'].value
updater.read('settings.ini')
updater['Trading Settings']['minimum_offer'].value = number_1.get()
updater.update_file()
updater.read('settings.ini')
updater['Trading Settings']['maximum_offer'].value = number_2.get()
updater.update_file()
if str(number_1) > 4:
print("Number can only exceed to 4")
updater.read('settings.ini')
updater['Trading Settings']['minimum_offer'].value = 4
updater.update_file()
You can't compare a string to a number. Use:
if float(number_1.get()) > 4:
You can also use int(), but if some joker enters a decimal point, this will prevent errors.
if (constant.gc in file.sheet_names):
coll = db[constant.gc]
print("Adding to " + constant.gc + " database")
df = file.parse(constant.gc)
df = clean(df)
data_dict = df.to_dict('r')
try:
result = coll.insert_many(data_dict)
nr_inserts = len(result.inserted_ids)
print(str(nr_inserts) + "Cases added to database")
except pymongo.errors.BulkWriteError as bwe:
nr_inserts = bwe.details["nInserted"]
print(nr_inserts)
I keep getting a NaTType error and I can't find which row of the dataframe has the blank date. Unfortunately, it's off of a 39k row Excel file. So, just looking through isn't going to help. I tried an except that theoretically could tell me how many were successfully inserted until the error, and therefore give me a hint on where to look, but it hasn't printed.
The error looks like this:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "dataimport.py", line 71, in importFromExcel
result = coll.insert_many(data_dict)
File "C:\Python38\lib\site-packages\pymongo\collection.py", line 758, in insert_many
blk.execute(write_concern, session=session)
File "C:\Python38\lib\site-packages\pymongo\bulk.py", line 511, in execute
return self.execute_command(generator, write_concern, session)
File "C:\Python38\lib\site-packages\pymongo\bulk.py", line 345, in execute_command
client._retry_with_session(
File "C:\Python38\lib\site-packages\pymongo\mongo_client.py", line 1384, in _retry_with_session
return func(session, sock_info, retryable)
File "C:\Python38\lib\site-packages\pymongo\bulk.py", line 339, in retryable_bulk
self._execute_command(
File "C:\Python38\lib\site-packages\pymongo\bulk.py", line 295, in _execute_command
result, to_send = bwc.execute(ops, client)
File "C:\Python38\lib\site-packages\pymongo\message.py", line 898, in execute
request_id, msg, to_send = self._batch_command(docs)
File "C:\Python38\lib\site-packages\pymongo\message.py", line 890, in _batch_command
request_id, msg, to_send = _do_bulk_write_command(
File "C:\Python38\lib\site-packages\pymongo\message.py", line 1382, in _do_bulk_write_command
return _do_batched_op_msg(
File "C:\Python38\lib\site-packages\pymongo\message.py", line 1307, in _do_batched_op_msg
return _batched_op_msg(
File "pandas\_libs\tslibs\nattype.pyx", line 64, in pandas._libs.tslibs.nattype._make_error_func.f
ValueError: NaTType does not support utcoffset
At a guess, ValueError and BulkWriteError are not the same, so nInserted never prints. Does anyone have an idea of how to get the number of successful inserts before the failure?
I doubt that any inserts are performed as the error is likely occurring before the data is passed to mongodb to insert.
In any case, if you want to hunt down which row in the dataframe has the NaT value, try: (subsitute 'date' for your column containing the date)
null_df = df[pd.isnull(df['date'])]
print(null_df)
To remove null dated items use:
df = df[pd.notnull(df['date'])]
I wanted to make a text wiget in window, but saw this traceback:
Traceback (most recent call last):
File "D:/хрень на питоне/experement3.py", line 18, in <module>
vl=Text(root, width = 20, heigth = 100 , wrap = WORD)
File "C:\Users\Людмилп\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 3554, in __init__
Widget.__init__(self, master, 'text', cnf, kw)
File "C:\Users\Людмилп\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 2567, in __init__
self.tk.call(
_tkinter.TclError: unknown option "-heigth"
My code looked like this:
from tkinter import *
root=Tk()
root.geometry('400x300')
app=Frame(root)
app.grid(row=2,column=0,sticky=S)
bt=Button(app,text='''
First button
''')
bt.grid()
app1=Frame(root)
app1.grid(row=2,column=1,sticky=S)
bt1=Button(app1,text='''
Second button
''')
bt1.grid()
vlf=Frame(root)
vlf.grid(row=0,column=3)
vl=Text(root, width = 20, heigth = 100 , wrap = WORD)
vl.grid()
root.mainloop()
What could went wrong?
Please read your error messages carefully because they almost ever contain useful information. In this case it tells you that in line 18 where you initialise the Text widget you give it an option "heigth" which it can't take. This is due to the fact that you just misspelled "height" by switching "t" and "h" which can happen and is just human.
PS: Your english isn't bad, don't worry. ^^
So I'm trying to edit a csv file by writing to a temporary file and eventually replacing the original with the temp file. I'm going to have to edit the csv file multiple times so I need to be able to reference it. I've never used the NamedTemporaryFile command before and I'm running into a lot of difficulties. The most persistent problem I'm having is writing over the edited lines.
This part goes through and writes over rows unless specific values are in a specific column and then it just passes over.
I have this:
office = 3
temp = tempfile.NamedTemporaryFile(delete=False)
with open(inFile, "rb") as oi, temp:
r = csv.reader(oi)
w = csv.writer(temp)
for row in r:
if row[office] == "R00" or row[office] == "ALC" or row[office] == "RMS":
pass
else:
w.writerow(row)
and I get this error:
Traceback (most recent call last):
File "H:\jcatoe\Practice Python\pract.py", line 86, in <module>
cleanOfficeCol()
File "H:\jcatoe\Practice Python\pract.py", line 63, in cleanOfficeCol
for row in r:
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
So I searched for that error and the general consensus was that "rb" needs to be "rt" so I tried that and got this error:
Traceback (most recent call last):
File "H:\jcatoe\Practice Python\pract.py", line 86, in <module>
cleanOfficeCol()
File "H:\jcatoe\Practice Python\pract.py", line 67, in cleanOfficeCol
w.writerow(row)
File "C:\Users\jcatoe\AppData\Local\Programs\Python\Python35-32\lib\tempfile.py", line 483, in func_wrapper
return func(*args, **kwargs)
TypeError: a bytes-like object is required, not 'str'
I'm confused because the errors seem to be saying to do the opposite thing.
If you read the tempfile docs you'll see that by default it's opening the file in 'w+b' mode. If you take a closer look at your errors, you'll see that you're getting one on read, and one on write. What you need to be doing is making sure that you're opening your input and output file in the same mode.
You can do it like this:
import csv
import tempfile
office = 3
temp = tempfile.NamedTemporaryFile(delete=False)
with open(inFile, 'r') as oi, tempfile.NamedTemporaryFile(delete=False, mode='w') as temp:
reader = csv.reader(oi)
writer = csv.writer(temp)
for row in reader:
if row[office] == "R00" or row[office] == "ALC" or row[office] == "RMS":
pass
else:
writer.writerow(row)
I am trying to make a code that will ask for a user input and if that input is not given in a set amount of time will assume a default value and continue through the rest of the code without requiring the user to hit enter. I am running in Python 3.5.1 on Windows 10.
I have looked through: Keyboard input with timeout in Python, How to set time limit on raw_input, Timeout on a function call, and Python 3 Timed Input black boxing the answers but none of the answers are suitable as they are not usable on Windows (principally use of signal.SIGALRM which is only available on linux), or require a user to hit enter in order to exit the input.
Based upon the above answers however i have attempted to scrap together a solution using multiprocessing which (as i think it should work) creates one process to ask for the input and creates another process to terminate the first process after the timeout period.
import multiprocessing
from time import time,sleep
def wait(secs):
if secs == 0:
return
end = time()+secs
current = time()
while end>current:
current = time()
sleep(.1)
return
def delay_terminate_process(process,delay):
wait(delay)
process.terminate()
process.join()
def ask_input(prompt,term_queue,out_queue):
command = input(prompt)
process = term_queue.get()
process.terminate()
process.join()
out_queue.put(command)
##### this doesn't even remotly work.....
def input_with_timeout(prompt,timeout=15.0):
print(prompt)
astring = 'no input'
out_queue = multiprocessing.Queue()
term_queue = multiprocessing.Queue()
worker1 = multiprocessing.Process(target=ask_input,args=(prompt,term_queue,out_queue))
worker2 = multiprocessing.Process(target=delay_terminate_process,args=(worker1,timeout))
worker1.daemon = True
worker2.daemon = True
term_queue.put(worker2)
print('Through overhead')
if __name__ == '__main__':
print('I am in if statement')
worker2.start()
worker1.start()
astring = out_queue.get()
else:
print('I have no clue what happened that would cause this to print....')
return
print('returning')
return astring
please = input_with_timeout('Does this work?',timeout=10)
But this fails miserably and yields:
Does this work?
Through overhead
I am in if statement
Traceback (most recent call last):
File "C:\Anaconda3\lib\multiprocessing\queues.py", line 241, in _feed
obj = ForkingPickler.dumps(obj)
File "C:\Anaconda3\lib\multiprocessing\reduction.py", line 50, in dumps
cls(buf, protocol).dump(obj)
File "C:\Anaconda3\lib\multiprocessing\queues.py", line 58, in __getstate__
context.assert_spawning(self)
File "C:\Anaconda3\lib\multiprocessing\context.py", line 347, in assert_spawning
' through inheritance' % type(obj).__name__
RuntimeError: Queue objects should only be shared between processes through inheritance
Does this work?
Through overhead
I have no clue what happened that would cause this to print....
Does this work?Process Process-1:
Traceback (most recent call last):
File "C:\Anaconda3\lib\multiprocessing\queues.py", line 241, in _feed
obj = ForkingPickler.dumps(obj)
File "C:\Anaconda3\lib\multiprocessing\reduction.py", line 50, in dumps
cls(buf, protocol).dump(obj)
File "C:\Anaconda3\lib\multiprocessing\process.py", line 287, in __reduce__
'Pickling an AuthenticationString object is '
TypeError: Pickling an AuthenticationString object is disallowed for security reasons
Traceback (most recent call last):
File "C:\Anaconda3\lib\multiprocessing\process.py", line 254, in _bootstrap
self.run()
File "C:\Anaconda3\lib\multiprocessing\process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "C:\Anaconda3\saved_programs\a_open_file4.py", line 20, in ask_input
command = input(prompt)
EOFError: EOF when reading a line
Does this work?
Through overhead
I have no clue what happened that would cause this to print....
Traceback (most recent call last):
File "C:\Anaconda3\lib\multiprocessing\queues.py", line 241, in _feed
obj = ForkingPickler.dumps(obj)
File "C:\Anaconda3\lib\multiprocessing\reduction.py", line 50, in dumps
cls(buf, protocol).dump(obj)
File "C:\Anaconda3\lib\multiprocessing\queues.py", line 58, in __getstate__
context.assert_spawning(self)
File "C:\Anaconda3\lib\multiprocessing\context.py", line 347, in assert_spawning
' through inheritance' % type(obj).__name__
RuntimeError: Queue objects should only be shared between processes through inheritance
Process Process-2:
Traceback (most recent call last):
File "C:\Anaconda3\lib\multiprocessing\process.py", line 254, in _bootstrap
self.run()
File "C:\Anaconda3\lib\multiprocessing\process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "C:\Anaconda3\saved_programs\a_open_file4.py", line 16, in delay_terminate_process
process.terminate()
File "C:\Anaconda3\lib\multiprocessing\process.py", line 113, in terminate
self._popen.terminate()
AttributeError: 'NoneType' object has no attribute 'terminate'
I really don't understand the multiprocessing module well and although I have read the official docs am unsure why this error occurred or why it appears to have ran through the function call 3 times in the process. Any help on how to either resolve the error or achieve an optional user input in a cleaner manner will be much appreciated by a noob programmer. Thanks!