I am coding a program with Tkinter to calculate wind values. It takes Rwy Heading, Wind Direction and Wind Speed to calculate the wind whether headwind, tailwind or crosswind with the calculated relevant wind speed.
I get this error:
Traceback (most recent call last):
File "C:\Users\altug\Desktop\PROJECTS\ÇALIŞMA.py", line 40, in <module>
rwy_var= int(rwy)
ValueError: invalid literal for int() with base 10: ''
I both tried IntVar() and int(str) method to convert string into integer but it didn't sort out the problem.
Below you can find my code:
ent1 = Entry(root)
ent1.grid(row = 0, column = 1)
ent2 = Entry(root)
ent2.grid(row = 1, column = 1)
ent3 = Entry(root)
ent3.grid(row = 2, column = 1)
rwy = ent1.get()
wind_direction = ent2.get()
wind_speed = ent3.get()
rwy_var= IntVar()
wind_direction_var= IntVar()
wind_speed_var = IntVar()
rwy_var= int(rwy)
wind_direction_var= int(wind_direction)
wind_speed_var = int(wind_speed)
x = rwy_var - wind_direction_var
radx = math.radians(x)
sinx = math.sin(radx)
cosx = math.cos(radx)
def htwind():
txt.delete(0.0, "end")
b = rwy_var + 90
a = rwy_var - 90
if b > 360:
b -= 360
elif a <0:
a+= 360
if x == abs(90):
result = 0
txt.insert(0.0, result +'\n')
elif a <= wind_direction_var or wind_direction_var<= b :
sh = wind_speed_var * cosx
result = "Headwind"+ " " + round(abs(sh))+ " " + "kt"
txt.insert(0.0, result +'\n')
elif a >= wind_direction_var or wind_direction_var >= b :
st = wind_speed_var * cosx
result = "Tailwind"+ " " + round(abs(st))+ " " + "kt"
txt.insert(0.0, result +'\n')
return ""
def xwind():
txt.delete(0.0, "end")
c=rwy_var-180
d= rwy_var + 180
if d > 360:
d -= 360
elif c<0:
c+= 360
if x == 0 or x == abs(180) or y == 0 or y == abs(180):
print("0")
elif c< wind_direction_var:
sxwl = wind_speed_var * sinx
rslt = "L"+""+round(abs(sxwl))+""+"kt"
txt.insert(0.0, rslt +'\n')
elif wind_direction_var<d:
sxwr = wind_speed_var * sinx
rslt = "R"+""+round(abs(sxwr))+""+"kt"
txt.insert(0.0, rslt +'\n')
return ""
txt = Text(root, width=6, height=2, wrap =WORD)
txt.grid(row =1, column = 1)
button_1 =Button(root, text = "search", command=lambda:[htwind(),xwind()])
button_1.grid(row =0, column = 5)
What is my mistake ?
Thanks in advance.
The IntVar is special in that it can't be directly converted to an int. To get its int value, do
rwy_var = rwy.get()
Related
I begin to code the python and I am not have more experience in syntax of python
I want to send a value from the RFID reader. If it saves successfully, the PIR Motion Sensor will be disabled in a moment. and reworking within the specified time.
If the temperature is measured And send the value to the function RFID Reader to record the temperature and the PIR Motion Sensor stops working as well.
class Security:
global dbHost
global dbUser
global dbPass
global dbNameEmp
global dbNameSecure
dbHost = 'localhost'
dbUser = 'root'
dbPass = 'iTdev#2020'
dbNameEmp = 'empinfo'
dbNameSecure = 'secureinfo'
def __init__(self):
self.msg=""
def Temperature(self):
while True:
GPIO.output(TRIG, False)
time.sleep(0.5)
GPIO.output(TRIG, True)
time.sleep(0.01)
GPIO.output(TRIG, False)
while GPIO.input(ECHO) == 0 :
pulse_start = time.time()
while GPIO.input(ECHO) == 1 :
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 11150
distance = round(distance,2)
if distance > 0 and distance < 3 :
buzzer.on()
time.sleep(0.1)
buzzer.off()
print ("Distance: %scm" % (distance))
#print "Ambient Temperature :", sensor.get_ambient()
print ("Temperature: %.1fc" % (sensor.get_object_1()))
msgTemp = ("%.1f" % (sensor.get_object_1()))
w, h = textsize(msgTemp, font=proportional(CP437_FONT))
if w <= device.width:
x = round((device.width - w) / 2)
with canvas(device) as draw:
text(draw, (x, 0), msgTemp, fill="white", font=proportional(CP437_FONT))
else:
show_message(device, msgTemp, fill="white", font=proportional(CP437_FONT),scroll_delay=0.04)
time.sleep(1)
device.clear()
def rfid_callback(self, state, dev):
rfid_presented = ""
keys = "X^1234567890XXXXqwertzuiopXXXXasdfghjklXXXXXyxcvbnmXXXXXXXXXXXXXXXXXXXXXXX"
while True:
r,w,x = select([dev], [], [])
for event in dev.read():
if event.type==1 and event.value==1:
if event.code==28:
rfid_presented = rfid_presented.replace("X", "")
travel = state.replace("Thread-", "")
dbConnEmp = mysql.connect(host=dbHost, user=dbUser, passwd=dbPass, db=dbNameEmp)
curEmp = dbConnEmp.cursor()
curEmp.execute("Select RFidEmp FROM RFidMaster WHERE (RFidStatus = 1) AND RFidNumber = '%s'" % (rfid_presented))
resultRFid = curEmp.fetchone()
if curEmp.rowcount != 1:
# print("Access Denied." + travel)
with canvas(device) as draw:
text(draw, (0, 0), "None", fill="white", font=proportional(CP437_FONT))
time.sleep(0.5)
device.clear()
else:
# print("Unlocking Door." + travel)
dbConnSecure = mysql.connect(host=dbHost, user=dbUser, passwd=dbPass, db=dbNameSecure)
curSecure = dbConnSecure.cursor()
curSecure.execute("SELECT EntraId,DATE_FORMAT(CreateDate, '%Y%m%d') AS CreateDate FROM entranlog ORDER BY EntraId DESC, CreateDate DESC LIMIT 1")
resultKey = curSecure.fetchone()
KeyDate = time.strftime("%Y%m%d")
if curSecure.rowcount != 1:
KeyId = KeyDate+"0001"
else:
if resultKey[1] == KeyDate:
iSum = int(resultKey[0])
def sum(x, y):
return x + y
KeyId = ('%d' % sum(iSum, 1))
else:
KeyId = KeyDate+"0001"
create_date = time.strftime('%Y-%m-%d %H:%M:%S')
insertSecure = "INSERT INTO entranlog (EntraId,EntraAction,EntraStatus,CreateBy,CreateDate) VALUES (%s,%s,%s,%s,%s)"
valSecure = (KeyId,travel,1,resultRFid[0],create_date)
curSecure.execute(insertSecure, valSecure)
dbConnSecure.commit()
# print("Welcome: " + resultRFid[0])
with canvas(device) as draw:
text(draw, (0, 0), "Hello", fill="white", font=proportional(CP437_FONT))
print(curSecure.rowcount, "record inserted.")
time.sleep(0.8)
device.clear()
rfid_presented = ""
else:
rfid_presented += keys[ event.code ]
def PirSensor(self):
while True:
led_blue.on()
time.sleep(0.1)
current_state = GPIO.input(pir_sensor)
if current_state == 1:
print("GPIO pin %s is %s" % (pir_sensor, current_state))
GPIO.output(relay_alarm,True)
led_blue.off()
led_red.blink(0.1, 0.2)
# buzzer.beep(0.5, 0.5, 3)
time.sleep(5)
GPIO.output(relay_alarm,False)
led_red.off()
led_yellow.blink(0.5, 0.5)
time.sleep(5)
led_yellow.off()
def main(self):
devIn = threading.Thread(target=self.rfid_callback, args=['1', InputDevice('/dev/input/event0')])
devIn.start()
devOut = threading.Thread(target=self.rfid_callback, args=['2', InputDevice('/dev/input/event1')])
devOut.start()
Pir = threading.Thread(target=self.PirSensor)
Pir.start()
Temp = threading.Thread(target=self.Temperature)
Temp.start()
if __name__ == "__main__":
g=Security()
g.main()
this code is in referrence to a cricket scoring program
When a button is pressed in my program, it runs a validation based of the users input and if it goes through, it should open a new window. But every time I run the code, the window.
def team_names(team):
global team_amount
global team_name_input
global team_amount_test
team_name_input = Toplevel(master)
confirm_screen.withdraw()
enter_names = Label(team_name_input, text = "Enter amount of players in " + team).grid(row = 0, column = 1)
enter_names2 = Label(team_name_input, text="(Between 2 and 11)").grid(row=1, column=1)
team_amount_test = Entry(team_name_input, width = 20)
team_amount_test.grid(row = 2, column = 1)
submit_amount = Button(team_name_input, text="Submit", command= lambda:amount_validation(team_1_array)).grid(row=3, column=1) <--- Button to open new winodw
def amount_validation(team_array):
team_num = 1
team_amount = int(team_amount_test.get())
if team_num == 1:
current_team = team_1
elif team_num == 2:
current_team = team_2
#Validation
if team_amount < 2 or team_amount > 11:
error = Label(team_name_input, text = "Invalid amount, try again").grid(row = 4, column = 1)
elif team_amount > 2 or team_amount < 11:
player_num = 1
name_input_win = Toplevel(master) #Should open new winodw here
#name_input_win.geometry("200x150")
team_name_input.withdraw()
first = Label(name_input_win, text = "Enter player " + str(player_num) + " for " + str(current_team)).grid(row = 0, column = 1)
name_input = Entry(name_input_win)
name_input.grid(row = 1, column = 1)
name = str(name_input.get())
for i in range(0, player_num):
p = None
while not p or p in team_array:
#first = Label(name_input, text="Enter player " + str(player_num) + " for " + str(current_team)).grid(row=0,column=1)
if p in team_array:
error = Label(name_input, text = "Player already entered").grid(row = 2, column = 1)
team_array.append(p)
player_num = player_num + 1
Any help will be appriciated ^-^
This was working and now has stopped and is giving me an error I can't see what's wrong with it?
def grade(R):
x = str(R)
if 'Practitioner' in x:
y = x.replace('Practitioner', ' ')
elif 'P' in x:
y = x.replace('P', ' ')
elif 'p' in x:
y = x.replace('p', ' ')
elif 'Graduate' in x:
y = x.replace('Graduate', ' ')
elif 'G' in x:
y =x.replace('G', ' ')
elif 'g' in x:
y = x.replace('g', ' ')
y = int(y)
g = inf.number_to_words(y)
return (g)
Full Script
import datetime
import os
from random import choice
from string import digits
import subprocess
import inflect
import pandas as pd
import reportlab
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas
# import xlrd
from reportlab.lib.units import mm
# set inflect
inf = inflect.engine()
# set fonts
folder = os.path.dirname(reportlab.__file__) + os.sep + 'fonts'
ttfFile_b = os.path.join(folder, 'VeraBd.ttf')
ttfFile_r = os.path.join(folder, 'Vera.ttf')
pdfmetrics.registerFont(TTFont("VeraBd", ttfFile_b))
pdfmetrics.registerFont(TTFont("Vera", ttfFile_r))
# Set date usage stuff
w = datetime.datetime.now()
d = datetime.date.today()
m = d.month
y = d.year + 1
p = str(w.hour) + '-' + str(w.minute) + '_' + str(w.second)
end_date = str(m) + '/' + str(y)
def grade(R):
x = str(R)
if 'Practitioner' in x:
y = x.replace('Practitioner', ' ')
elif 'P' in x:
y = x.replace('P', ' ')
elif 'p' in x:
y = x.replace('p', ' ')
elif 'Graduate' in x:
y = x.replace('Graduate', ' ')
elif 'G' in x:
y =x.replace('G', ' ')
elif 'g' in x:
y = x.replace('g', ' ')
y = int(y)
g = inf.number_to_words(y)
return (g)
def level(R):
x = str(R)
y = x.replace('Practitioner', ' ')
int(y)
g = inf.number_to_words(y)
return (g)
# Routine to get location
def location(L):
x = str(L)
if 'London' in x:
l = str("London")
elif 'Stratford' in x:
l = str("Stratford Upon Avon")
elif 'Bristol' in x:
l = str("Bristol")
elif 'Penrith' in x:
l = str("Penrith")
else:
l = str("United Kingdom")
return (l)
# Get date
def when(D):
dt = D.strftime('%d %B %Y')
d = str(dt)
return (d)
# get random diploma number
def dip():
x = ''.join(choice(digits) for i in range(6))
k = str(x)
return (k)
def p_certs(df):
# set PDF file name and canvas size
# file_location = 'C:\Users\Suely\Desktop\Ouput_PDF\'
# Set date usage stuff
w = datetime.datetime.now()
d = datetime.date.today()
m = d.month
y = d.year + 1
p = str(w.hour) + '-' + str(w.minute) + '_' + str(w.second)
# end_date = str(m) + '/' + str(y)
file_name = 'CERTIFICATES_' + str(d) + '_' + str(p) + '.pdf'
c = canvas.Canvas(file_name, pagesize=(210 * mm, 297 * mm))
# 1mm = 0.35277777 pt
# draw each page
for index, row in df.iterrows():
# D = str(row['Date'])
# R = row['Grading Level (National Grading)']
# L = row['Select Grading Event']
# g = location(L)
# A = row['Grading Committee']
# I = row['Instructor']
g = row['Location']
fn = str.strip(row['First Name'])
ln = str.strip(row['Last Name'])
f = row['Grade']
# r = row['Grade']
r = grade(f)
# d = str('11 August 2018')
# d = when(D)
d = str(row['Date'])
N = fn + ' ' + ln
# N = row['First Name'] + ' ' + row['Last Name']
# N = row['First Name'] + row['Last Name']
k = dip()
#k2 = str('KMG-UK -') + str(k)
k2 = row['Diploma Number']
# Draw Name
c.setFont('VeraBd', 24, leading=None)
c.drawCentredString(297.63786, 160 * mm, str.title(N))
# Draw Grade
c.setFont('VeraBd', 18, leading=None)
c.drawCentredString(110 * mm, 130 * mm, str.upper(r))
# Draw Place
c.setFont('VeraBd', 14, leading=None)
# c.drawCentredString(297.63786, 261.8581643, str.title(g))
c.drawCentredString(105 * mm, 91 * mm, str.upper(g))
# Draw Date
c.setFont('VeraBd', 14, leading=None)
# c.drawCentredString(297.63786, 236.3463527, str.title(d))
c.drawCentredString(105 * mm, 81 * mm, str(d))
# Draw Diploma number
c.setFont('VeraBd', 11, leading=None)
c.drawCentredString(105 * mm, 71 * mm, str.upper(k2))
c.showPage()
# Draw Administration & Instructor
# c.setFont('VeraBd', 12, leading=None)
# c.drawCentredString(60*mm, 25*mm, str.upper(I))
# c.setFont('VeraBd', 12, leading=None)
# c.drawCentredString(105*mm, 25*mm, str.upper(A))
c.save()
subprocess.Popen([file_name], shell=True)
# set data file
data_location = '007. P1_P2 Data Sheet.csv'
file_name2 = '007. P1_P2 Data Sheet.xlsx'
# read dataframe
df = pd.read_csv(data_location, encoding='latin1', na_values=['nan'], keep_default_na=False)
# df = pd.read_excel(file_name2, 'Sheet1', index_col=None, na_values=['NA'])
p_certs(df)
The Error
C:\Users\James\AppData\Local\Programs\Python\Python37\python.exe "D:/Dropbox/Dropbox/00000001 Licence Print/P certs/002 P1 Certificates/Certificatea.py"
Traceback (most recent call last):
File "D:/Dropbox/Dropbox/00000001 Licence Print/P certs/002 P1 Certificates/Certificatea.py", line 179, in
p_certs(df)
File "D:/Dropbox/Dropbox/00000001 Licence Print/P certs/002 P1 Certificates/Certificatea.py", line 127, in p_certs
r = grade(f)
File "D:/Dropbox/Dropbox/00000001 Licence Print/P certs/002 P1 Certificates/Certificatea.py", line 50, in grade
y = int(y)
UnboundLocalError: local variable 'y' referenced before assignment
Process finished with exit code 1
Your local variable y would not be initialized before its usage in the statement y = int(y) if none of the if and elif conditions before it are met.
You can assign to y a default value in an else clause instead:
def grade(R):
x = str(R)
if 'Practitioner' in x:
y = x.replace('Practitioner', ' ')
elif 'P' in x:
y = x.replace('P', ' ')
elif 'p' in x:
y = x.replace('p', ' ')
elif 'Graduate' in x:
y = x.replace('Graduate', ' ')
elif 'G' in x:
y =x.replace('G', ' ')
elif 'g' in x:
y = x.replace('g', ' ')
else:
y = '0'
y = int(y)
g = inf.number_to_words(y)
return (g)
Or you can try fixing your input data to ensure that the argument R would always result in satisfying one of the conditions in the if and elif clauses.
I am struggling with a very simple loop that perfectly works if run "standalone", but doesn't work anymore if I use it as an outer loop for many other instructions (which also perfectly work if run standalone for only 1 iteration).
The simple outer loop is a
for i in range(0,somevalue):
do some inner instructions
Here is the full code, which perfectly works if I put a range of dimension 1, whilst it never ends if I put even a simple range of dimension 2:
import numpy as np
import numpy.ma as ma
import random
import matplotlib.pyplot as plt
i = int
x = np.zeros(1440)
class_x = np.zeros(1440)
w1 = np.array([0,6*60])
w2 = np.array([20*60,23*60])
x[w1[0]:(w1[1])] = np.full(np.diff(w1),0.001)
x[w2[0]:(w2[1])] = np.full(np.diff(w2),0.001)
x_masked = np.zeros_like(ma.masked_not_equal(x,0.001))
c = 10
func_time = 300
max_free_spot = int
i = 0
for i in range(0,1):
tot_time = 0
switch_count = 0
switch_ons = []
while
tot_time <= func_time:
switch_on = random.choice([random.randint(w1[0],(w1[1]-c)),random.randint(w2[0],(w2[1]-c))])
if x[switch_on] == 0.001:
if switch_on in range(w1[0],w1[1]):
if np.any(x[switch_on:w1[1]]!=0.001):
next_switch = [switch_on + k[0] for k in np.where(x[switch_on:]!=0.001)]
if (next_switch[0] - switch_on) >= c and max_free_spot >= c:
upper_limit = min((next_switch[0]-switch_on),min(func_time,w1[1]-switch_on))
elif (next_switch[0] - switch_on) < c and max_free_spot >= c:
continue
else: upper_limit = next_switch[0]-switch_on
else:
upper_limit = min(func_time,w1[1]-switch_on) #max random length of cycle
if upper_limit >= c:
indexes = np.arange(switch_on,switch_on+(random.randint(c,upper_limit)))
else:
indexes = np.arange(switch_on,switch_on+upper_limit)
else:
if np.any(x[switch_on:w2[1]]!=0.001):
next_switch = [switch_on + k[0] for k in np.where(x[switch_on:]!=0.001)]
if (next_switch[0] - switch_on) >= c:
upper_limit = min((next_switch[0]-switch_on),min(func_time,w2[1]-switch_on))
elif (next_switch[0] - switch_on) < c and max_free_spot >= c:
continue
else: upper_limit = next_switch[0]-switch_on
else:
upper_limit = min(func_time,w2[1]-switch_on)
if upper_limit >= c:
indexes = np.arange(switch_on,switch_on+(random.randint(c,upper_limit)))
else:
indexes = np.arange(switch_on,switch_on+upper_limit)
tot_time = tot_time + indexes.size
switch_ons.append(switch_on)
if tot_time > func_time:
indexes_adj = indexes[:-(tot_time-func_time)]
coincidence = random.randint(1,5)
np.put(x_masked,indexes_adj,(2*coincidence),mode='clip')
np.put(x,indexes_adj,(2*coincidence))
x_masked = np.zeros_like(ma.masked_greater_equal(x_masked,0.001))
tot_time = (tot_time - indexes.size) + indexes_adj.size
switch_count = switch_count + 1
break
else:
coincidence = random.randint(1,5)
np.put(x_masked,indexes,(2*coincidence),mode='clip')
np.put(x,indexes,(2*coincidence))
x_masked = np.zeros_like(ma.masked_greater_equal(x_masked,0.001))
tot_time = tot_time
switch_count = switch_count + 1
free_spots = []
for j in ma.notmasked_contiguous(x_masked):
free_spots.append(j.stop-j.start)
max_free_spot = max(free_spots)
class_x = class_x + x
plt.plot(class_x)
Any help is really really appreciated
I have been trying to get this to work for over a week now and cant seem to get it to choose the best possible move. Can someone take a look and help me out? I feel like I have missed something stupid.
Thanks!
from tkinter import *
import tkinter.messagebox
tk = Tk()
tk.title("Tic Tac Toe")
click = True
X = "X"
O = "O"
EMPTY = " "
TIE = "TIE"
NUM_SQUARES = 9
def new_board():
"""Create new game board."""
board = []
for square in range(NUM_SQUARES):
board.append(EMPTY)
return board
def Player1Win(board, i):
if(board[0]==1 and board[1]==1 and board[2]==1)or(board[0]==1 and board[3]==1 and board[6]==1)or(board[2]==1 and board[5]==1 and board[8]==1)or(board[3]==1 and board[4]==1 and board[5]==1)or(board[6]==1 and board[7]==1 and board[8]==1)or(board[0]==1 and board[4]==1 and board[8]==1)or(board[2]==1 and board[4]==1 and board[6]==1)or(board[1]==1 and board[4]==1 and board[7]==1)or(board[0]==1 and board[3]==1 and board[6]==1):
if(i==0):
tkinter.messagebox.showinfo("Winner X won")
return True
else:
return False
def Player2Win(board, i):
if(board[0]==0 and board[1]==0 and board[2]==0)or(board[0]==0 and board[3]==0 and board[6]==0)or(board[2]==0 and board[5]==0 and board[8]==0)or(board[3]==0 and board[4]==0 and board[5]==0)or(board[6]==0 and board[7]==0 and board[8]==0)or(board[0]==0 and board[4]==0 and board[8]==0)or(board[2]==0 and board[4]==0 and board[6]==0)or(board[1]==0 and board[4]==0 and board[7]==0):
if(i==0):
tkinter.messagebox.showinfo("Winner O won")
return True
else:
return False
board2=new_board()
board=new_board()
def legal_moves(board):
"""Create list of legal moves."""
moves = []
count = 0
for square in range(NUM_SQUARES):
if board[square] == EMPTY:
count += 1
moves.append(square)
print(count)
return moves
def minimax(board2):
global click
#Get all possible steps
moves=legal_moves(board2)
#Check copy board to win
if(Player1Win(board2,2) == True):
return 10
if(Player2Win(board2,2) == True):
return -10
if(len(moves)==0):
return 0
j = 1000
for i in moves:
if click:
click=True #change to Player X
board2[i]=0 #This is a copy of the board is not the main
else:
click=False #to change Player O
board2[i]=1 #This is a copy of the board is not the main
v = minimax(board2) # Recursive call functions
# # Select the minimum number for O and maximum for X
if j == 1000 or (click == False and j < v) or (click == True and v < j):
j = v
if click:
return j-1 # If player O
else:
return j+1 # If player X
def bestMove():
global click
# Get all possible steps
moves=legal_moves(board)
# Move all the data from the main board
for k in range(NUM_SQUARES):
board2.append(board[k])
j = 1000
best = -1
for i in moves:
if click:
click = False #change to Player X
board2[i]=0
else:
click = True #change to Player O
board2[i]=1
v = minimax(board2)
# Select the minimum number for O and maximum for X
if j == 1000 or (click == False and j < v) or (click == True and v < j):
j = v
best = i
return best
def Update(board):
global click
if button1["text"]=="X":
board[0]=1
if button2["text"]=="X":
board[1]=1
if button3["text"]=="X":
board[2]=1
if button4["text"]=="X":
board[3]=1
if button5["text"]=="X":
board[4]=1
if button6["text"]=="X":
board[5]=1
if button7["text"]=="X":
board[6]=1
if button8["text"]=="X":
board[7]=1
if button9["text"]=="X":
board[8]=1
if button1["text"]=="O":
board[0]=0
if button2["text"]=="O":
board[1]=0
if button3["text"]=="O":
board[2]=0
if button4["text"]=="O":
board[3]=0
if button5["text"]=="O":
board[4]=0
if button6["text"]=="O":
board[5]=0
if button7["text"]=="O":
board[6]=0
if button8["text"]=="O":
board[7]=0
if button9["text"]=="O":
board[8]=0
def move(i):
global click
click = False
if i == 0:
button1["text"] = "O"
board[0]=0
elif i == 1:
button2["text"] = "O"
board[1]=0
elif i == 2:
button3["text"] = "O"
board[2]=0
elif i == 3:
button4["text"] = "O"
board[3]=0
elif i == 4:
button5["text"] = "O"
board[4]=0
elif i == 5:
button6["text"] = "O"
board[5]=0
elif i == 6:
button7["text"] = "O"
board[6]=0
elif i == 7:
button8["text"] = "O"
board[7]=0
elif i == 8:
button9["text"] = "O"
board[8]=0
def checker(buttons):
global click
if buttons["text"] == " ":
buttons["text"] = "X"
click = True
Update(board)
best = bestMove()
move(best)
Player1Win(board, 0)
Player2Win(board, 0)
buttons = StringVar()
button1 = Button(tk,text=" ",font=('Times 26 bold'), height = 4, width = 8, command =lambda:checker(button1))
button1.grid(row=1,column=0,sticky = S+N+E+W)
button2 = Button(tk,text=" ",font=('Times 26 bold'), height = 4, width = 8, command =lambda:checker(button2))
button2.grid(row=1,column=1,sticky = S+N+E+W)
button3 = Button(tk,text=" ",font=('Times 26 bold'), height = 4, width = 8, command =lambda:checker(button3))
button3.grid(row=1,column=2,sticky = S+N+E+W)
button4 = Button(tk,text=" ",font=('Times 26 bold'), height = 4, width = 8, command =lambda:checker(button4))
button4.grid(row=2,column=0,sticky = S+N+E+W)
button5 = Button(tk,text=" ",font=('Times 26 bold'), height = 4, width = 8, command =lambda:checker(button5))
button5.grid(row=2,column=1,sticky = S+N+E+W)
button6 = Button(tk,text=" ",font=('Times 26 bold'), height = 4, width = 8, command =lambda:checker(button6))
button6.grid(row=2,column=2,sticky = S+N+E+W)
button7 = Button(tk,text=" ",font=('Times 26 bold'), height = 4, width = 8, command =lambda:checker(button7))
button7.grid(row=3,column=0,sticky = S+N+E+W)
button8 = Button(tk,text=" ",font=('Times 26 bold'), height = 4, width = 8, command =lambda:checker(button8))
button8.grid(row=3,column=1,sticky = S+N+E+W)
button9 = Button(tk,text=" ",font=('Times 26 bold'), height = 4, width = 8, command =lambda:checker(button9))
button9.grid(row=3,column=2,sticky = S+N+E+W)
tk.mainloop()
print ("Please Begin Play")
I would suggest you add print statements to see what is happening. Start with printing "click" for each pass through the for() loop and also print what the return (j +- 1) and the value for "i" right before the return statements (and please don't use "i", "l", or "O" as single digit variable names as they can look like numbers, i.e, o=1, o=l). You can handle the really, really long and really, really, confusing line a lot better with a list of win combinations.
## a simple example that will require some modification by you
def check_for_winner(player, board):
## fill in the rest yourself
win_combos=[[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 4, 8], [0, 3, 6]]
for x, y, z in win_combos:
print "checking", x, y, z
if board[x] == board[y] == board[z]:
print "**** We have a winner", player, x, y, z
return True
return False